简体   繁体   中英

NA for 1 particular date when converting dates from "character" format to "POSIXct" with as.POSIXct

I'm converting a string vector to date format with as.POSIXct(). Here is the strange thing:

as.POSIXct("2017-03-26 03:00:00.000",format="%Y-%m-%d %H")

#Gives

"2017-03-26 03:00:00 CEST"

#While

as.POSIXct("2017-03-26 02:00:00.000",format="%Y-%m-%d %H")

#Outputs
NA

This is really confusing and frustrating. It seem like the function really doesn't like the specific time: 02:00:00.000

We can specify the %T for time. In the format, there are minutes, seconds and millseconds. So, the %H is only matching the hour part

as.POSIXct("2017-03-26 02:00:00.000",format="%Y-%m-%d %T")
[1] "2017-03-26 02:00:00 EDT"

Or to take care of the milliseconds as well

as.POSIXct("2017-03-26 02:00:00.000",format="%Y-%m-%d %H:%M:%OS")
#[1] "2017-03-26 02:00:00 EDT"

Or using lubridate

library(lubridate)
ymd_hms("2017-03-26 02:00:00.000")

This was a daylight savings issue, the time:

"2017-03-26 02:00:00.000" does not exist in Sweden as we lost an hour this date when changing to "summer time".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM