POSIXct类中的毫秒数

use*_*131 13 r posixct

如何正确解析毫秒?

as.POSIXct 功能在我的环境中如下工作.

> 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"

我的R版本是适用于Windows的x86 v3.0.2.

Ric*_*ton 22

指定输入格式,%OS用于表示带小数部分的秒数.

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")
Run Code Online (Sandbox Code Playgroud)

当您显示该值时,请在格式字符串中附加0到6之间的数字,以告知R要显示的小数秒数.

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

(注意,你得到舍入错误,并且R的日期时间格式总是向下舍入,所以如果你显示更少的小数位,有时看起来你已经失去了一毫秒.)

日期时间格式记录在?strptime帮助页面上.相关段落是:

 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.
Run Code Online (Sandbox Code Playgroud)