简体   繁体   中英

combine different columns of date and time into one column as a date time

I have a bunch of character date and times that I would like to merge into 1 column of date time.

For example I have:

Date           Time
1/1/2018       2:00:00 PM
1/1/2018       9:00:00 AM

I would like the result to end like:

Date time
2018-01-01 14:00:00
2018-01-01 9:00:00

I first tried

paste(Date,Time)

but then I realized it does not take 'PM' into account when combining the two columns.

What should I do to merge the two columns in the correct format?

We can use use as.POSIXct after paste ing the 'Date' and 'Time' columns (assuming that the Date format is month/day/year)

datetime <- with(df1, as.POSIXct(paste(Date, Time), 
            format = "%m/%d/%Y %I:%M:%S %p"))
data.frame(datetime)
#             datetime
#1 2018-01-01 14:00:00
#2 2018-01-01 09:00:00

data

df1 <- structure(list(Date = c("1/1/2018", "1/1/2018"), Time = c("2:00:00 PM", 
"9:00:00 AM")), class = "data.frame", row.names = c(NA, -2L))

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