Search code examples
rtimestampposixctposixlt

How to convert string "2019-10-09T06:07:05.888Z" as calendar date and time


Please help me to find a solution for converting "2019-10-09T06:07:05.888Z" as a calendar time stamp. I tried the following methods,

> format(as.POSIXlt("2019-10-09T06:07:05.888Z"), "%Y-%m-%d %H:%M:%OS3")
[1] "2019-10-09 00:00:00.000"

> as.POSIXct("2019-10-09T06:07:05.888Z", format="%Y-%m-%d %H:%M:%OS")
[1] NA

Solution

  • With as.POSIXct, we can first convert the data into POSIXct class and then use format to display the output in the format we want.

    temp <- as.POSIXct("2019-10-09T06:07:05.888Z",format = "%Y-%m-%dT%H:%M:%OS", tz = "UTC")
    format(temp, "%Y-%m-%d %H:%M:%OS3")
    #[1] "2019-10-09 06:07:05.888"
    

    Or with lubridate

    format(lubridate::ymd_hms("2019-10-09T06:07:05.888Z"), "%Y-%m-%d %H:%M:%OS3")