简体   繁体   中英

Removing time stamp to include just the month and day

I have a table called "rejected_at" in the dataframe "Job_applications". The format is: "M/DD/YYYY H:M:S PM/AM". Now i want to create a new table that just has "M/DD". How would i do this? enter image description here

We can convert to DateTime class and then extract the month and day

v1 <- as.POSIXct(df1$rejected_at, "%m/%d/%Y %H:%M:%S")
format(v1, "%d")
format(v1, "%m")

Or if we the format needed is %m/%d

format(v1, "%m/%d")

Or using tidyverse

library(dplyr)
library(lubridate)
df1 %>%
    mutate(rejected_at = mdy_hms(rejected_at),
           day = day(rejected_at),
           month = month(rejected_at))

Assuming the rejected_at column is just text, you could try using sub here:

x <- "12/30/2018 4:05:44 PM"
sub("/[^/]+$", "", x)

[1] "12/30"

Or, in your case:

Job_applications$new_col <- sub("/[^/]+$", "", Job_applications$rejected_at)

Edit:

If you also wanted to retain the year, then we can try using sub with a capture group targeting the full date:

sub("(\\d+/\\d+/\\d+).*", "\\1", x)

[1] "12/30/2018"

You can do it using lubridate

library(lubridate)

new_date <- mdy_hms("08/14/2017 09:59:06 PM")

new1 <- paste0(month(new_date),"/",day(new_date))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM