Search code examples
rdatetimeposixctposixlt

Using R, as.POSIXct() returning NAs even though it was working before


I am using R. This worked for me a month ago, but now when I try to run it I get NA. I have tried changing the timezone and I still receive NA. I am not sure why I am getting this issue

as.POSIXct("12:46 29-Nov-18",format = "%H:%M %m/%d/%y")
as.POSIXct("12:46 29-Nov-18",format = "%H:%M %m/%d/%y",tz= "GMT")

Solution

  • Several things wrong with your code, most of it fixed by reading ?strptime:

    • "%m" is the 2 digit (0-padded) integer for the month, not Nov, use %b instead
    • the string as dashes, not slashes, so %m/%d/%y should be %m-%d-%y
    • the string has date first, so %d-%m-%y would have been the correct order.

    Combine those three, and we have

    as.POSIXct("12:46 29-Nov-18",format = "%H:%M %d-%b-%y")
    # [1] "2018-11-29 12:46:00 EST"
    as.POSIXct("12:46 29-Nov-18",format = "%H:%M %d-%b-%y", tz = "GMT")
    # [1] "2018-11-29 12:46:00 GMT"