POSIXct 类中的毫秒

2024-02-16

如何正确解析毫秒?

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 版本是 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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

POSIXct 类中的毫秒 的相关文章

随机推荐