Search code examples
rstrptime

strptime returning NA


I am getting NA value for my date string using strptime in R. I looked at the various answers, but it didn't work. Here is my code

startDate=strptime("Wed May 25 01:51:32 UTC 2016", format="%a %B %d %H:%m:%S %Z %Y", tz="UTC")
print(startDate)

Any help would be appreciated.


Solution

  • "%H:%m:%S" should be "%H:%M:%S". Once you change that, you'll get an error because %Z is not valid for input.

    If all the datetime strings have UTC timezone, this will work:

    R> strptime("Wed May 25 01:51:32 UTC 2016", "%a %B %d %H:%M:%S UTC %Y", "UTC")
    [1] "2016-05-25 01:51:32 UTC"
    

    If not, then you can extract the year and prepend it to the string, because strptime will ignore all characters after those specified by the format string.

    R> dts <- "Wed May 25 01:51:32 UTC 2016"
    R> dtf <- "%Y %a %B %d %H:%M:%S"
    R> strptime(paste(substring(dts, nchar(dts)-3), dts), dtf, "UTC")
    [1] "2016-05-25 01:51:32 UTC"