如何使用
strptime
或任何其他函数来解析 R 中的毫秒时间戳?
time <- "2010-01-15 13:55:23.975"
time[1]
# [1] "2010-01-15 13:55:23.975"
strptime(time[1], format="%Y-%m-%d %H:%M:%S.%f")
# [1] NA
strptime(time[1], format="%Y-%m-%d %H:%M:%S")
# [1] "2010-01-15 13:55:23"`
由
?strptime
帮助文件提供(示例已更改为您的值):
> z <- strptime("2010-01-15 13:55:23.975", "%Y-%m-%d %H:%M:%OS")
> z # prints without fractional seconds
[1] "2010-01-15 13:55:23 UTC"
> op <- options(digits.secs=3)
> z
[1] "2010-01-15 13:55:23.975 UTC"
> options(op) #reset options
您还可以使用
strptime(time, "%OSn")
,其中 0 <= n <= 6, without having to set digits.secs
。
文档指出“其中支持哪些取决于操作系统。”所以YMMV。
无需设置
options(digits.secs=3)
即可实现此目的的另一个选项是使用 format()
:
format(Sys.time(), "%Y-%m-%d %H:%M:%OS3")
# using as.POSIXct to convert the string
format(as.POSIXct("2010-01-15 13:55:23.975"), "%Y-%m-%d %H:%M:%OS3")
# using strptime to convert the string
format(strptime("2010-01-15 13:55:23.975", "%Y-%m-%d %H:%M:%OS"), "%Y-%m-%d %H:%M:%OS3")