Moksh Moksh - 6 months ago 45
R Question

NA returned while using strptime

I have this data frame which gives me Date and Time columns. I am trying to combine these 2 columns but strptime is returning NA. i want to understand why is it happening?

x <- data.frame(date = "1/2/2007", time = "00:00:02")
y <- strptime(paste(x$date,x$time,sep = " "), format = "%b/%d/%y %H:%M:%S")


We need %m and %Y in place of %b and %y (%b - Abbreviated month name in the current locale on this platform. %y - Year without century (00–99)).

strptime(paste(x$date,x$time,sep = " "), "%m/%d/%Y %H:%M:%S")
#[1] "2007-01-02 00:00:02 IST"

For understanding the format, it is better to check ?strptime

Or we can use mdy_hms from lubridate

with(x, mdy_hms(paste(date, time)))
#[1] "2007-01-02 00:00:02 UTC"