POSIXct date conversion error [duplicate]

2019-03-01 10:24发布

问题:

This question already has an answer here:

  • R: strptime() and is.na () unexpected results 1 answer

I've encountered the following error when converting a set of dates in character format to a POSIXct object.

Example Data:

t<-c("3/11/2007 1:30", "3/11/2007 2:00", "4/11/2007 2:00")

str(t)

chr [1:3] "3/11/2007 1:30" "3/11/2007 2:00" "4/11/2007 2:00"

z<-as.POSIXct(strptime(t, format ="%m/%d/%Y  %H:%M"))

z
"2007-03-11 01:30:00 MST" NA                        "2007-04-11 02:00:00 MDT"

str(z)

POSIXct[1:3], format: "2007-03-11 01:30:00" NA "2007-04-11 02:00:00"

My question is why is the NA returned for the second date in z? I have a dataset that contains 8 years of hourly data (from which I copied the dates above), and this NA error pops up only for dates between 3/8 - 3/14 and ONLY when the hour is 02:00:00.

I do not encounter an error if the dates are converted to POSIXlt, so that is my current work around.

Any thoughts?

回答1:

Try using a time zone that does not use daylight savings time:

as.POSIXct(t, format = "%m/%d/%Y  %H:%M", tz = "GMT")
## [1] "2007-03-11 01:30:00 GMT" "2007-03-11 02:00:00 GMT" "2007-04-11 02:00:00 GMT"