Milliseconds in POSIXct Class
Solution 1:
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.