Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

r - Milliseconds in POSIXct Class

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...