Reputation: 85
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?
Upvotes: 1
Views: 672
Reputation: 886938
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
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))
Upvotes: 1