Search code examples
rdatetimetype-conversionposixct

NA result in converting string to POSIXct date time in R


Uploading csv file and converting a datetime from character to POSIXct I stumbled in a unexpected NA result:

as.POSIXct("20210328 02:00:00", format = "%Y%m%d %H:%M:%S")

this seems to happen only for this record... Any idea why? Thank you!


Solution

  • This might be related to Daylight savings in your local timezone, as.POSIXct uses local timezone by default. Try to use timezone as UTC.

    as.POSIXct("20210328 02:00:00", format = "%Y%m%d %H:%M:%S", tz = 'UTC')
    #[1] "2021-03-28 02:00:00 UTC"
    

    You can also use lubridate::ymd_hms which uses UTC timezone by default.

    lubridate::ymd_hms("20210328 02:00:00")