POSIXct类中的毫秒数

28

如何正确解析毫秒?

在我的环境中,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。

1个回答

38

使用%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")

在显示值时,将数字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"
(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.

在定义 y 时,format 参数并不是必需的。 - moodymudskipper

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接