etgriffiths
etgriffiths

Reputation: 276

as.POSIXct/as.POSIXlt doesn't like .61 milliseconds

Here's a weird artifact. I'm converting tens of thousands of character vectors into a datetime class, like so:

alles$DateTime=as.POSIXct(alles$roughdate, tz="EST",format="%Y%m%d.%H%M%S.%OS")

Pretty straight forward. The character string (alles$roughdate) is in the format YYYYMMDD.HHMMSS.ss with the .ss being milliseconds. The above code works, as would be expected. However, if the milliseconds equal .61, it returns an NA instead of a date time value.

This isn't too bad, but when dealing with tens of thousands cells, a few hundred are always returned as NA. Milliseconds always .61, doesn't matter what the rest of the date is. I do need those dates.

I've tried isolating those files and then merging the two data frames together again, but that doesn't seem to work. All of my dates are suddenly NA.

Any thoughts?

Example

vec <- c("20150101.010101.60", "20150101.010101.61", "20150101.010101.62") 
as.POSIXlt(vec, tz="EST", format="%Y%m%d.%H%M%S.%OS")
#[1] "2015-01-01 01:01:60 EST" NA "2015-01-01 01:01:01 EST"

Upvotes: 3

Views: 397

Answers (1)

nrussell
nrussell

Reputation: 18602

If you change the format for the time part to be %H%M%OS instead of %H%M%S.%OS, it seems to parse correctly. You may have to adjust your options so see this:

as.POSIXlt(vec, tz = "EST", format = "%Y%m%d.%H%M%OS")
#[1] "2015-01-01 01:01:01 EST" "2015-01-01 01:01:01 EST" 
#[3] "2015-01-01 01:01:01 EST"

options(digits.secs = 2)
as.POSIXlt(vec, tz = "EST", format = "%Y%m%d.%H%M%OS")
# [1] "2015-01-01 01:01:01.60 EST" "2015-01-01 01:01:01.61 EST"
# [3] "2015-01-01 01:01:01.62 EST"

Upvotes: 3

Related Questions