Milliseconds in POSIXct Class

user3355131 picture user3355131 · Feb 26, 2014 · Viewed 12.5k times · Source

How can I parse milliseconds correctly?

as.POSIXct function works as following in my environment.

> as.POSIXct("2014-02-24 11:30:00.001")
[1] "2014-02-24 11:30:00.000 JST"
> as.POSIXct("2014-02-24 11:30:00.0011")
[1] "2014-02-24 11:30:00.001 JST"

My R version is x86 v3.0.2 for Windows.

Answer

Richie Cotton picture Richie Cotton · Feb 26, 2014

Specify the input format, using %OS to represent the seconds with their fractional parts.

x <- c("2014-02-24 11:30:00.123", "2014-02-24 11:30:00.456")
y <- as.POSIXct(x, format = "%Y-%m-%d %H:%M:%OS")

When you come to display the value, append a number between 0 and 6 to the format string to tell R how many decimal places of seconds to display.

format(y, "%Y-%m-%d %H:%M:%OS6")
## [1] "2014-02-24 11:30:00.122999" "2014-02-24 11:30:00.456000"

(Note that you get rounding errors, and R's datetime formatting always rounds downwards, so if you show less decimal places it sometimes looks like you've lost a millisecond.)

Datetime formats are documented on the ?strptime help page. The relevant paragraph is:

 Specific to R is '%OSn', which for output gives the seconds
 truncated to '0 <= n <= 6' decimal places (and if '%OS' is not
 followed by a digit, it uses the setting of
 'getOption("digits.secs")', or if that is unset, 'n = 3').
 Further, for 'strptime' '%OS' will input seconds including
 fractional seconds.  Note that '%S' ignores (and not rounds)
 fractional parts on output.