【发布时间】:2014-02-26 09:52:22
【问题描述】:
如何正确解析毫秒?
as.POSIXct 函数在我的环境中工作如下。
我的 R 版本是 x86 v3.0.2 for Windows。
【问题讨论】:
如何正确解析毫秒?
as.POSIXct 函数在我的环境中工作如下。
我的 R 版本是 x86 v3.0.2 for Windows。
【问题讨论】:
指定输入格式,使用%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"
(请注意,您会遇到舍入错误,并且 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.
【讨论】: