R中的Delta时间戳解析(纳秒,微秒,毫秒) [英] Delta Timestamp Parsing in R (Nanoseconds, Microseconds, Milliseconds)
问题描述
我正在R中工作,需要将时间戳从我认为的纳秒精度更改为微秒精度或毫秒精度(我相信它必须是毫秒或仅十进制小数点后三位).
I am working in R and need to change the timestamp from what I believe is nanosecond precision to either microsecond precision or millisecond precision (I believe it needs to be milliseconds or only three digits past the decimal).
"2019-03-02D00:00:12.214841000"
部分困难是我认为没有像 lubridate
这样的程序包可以处理它.我不确定是否需要使用正则表达式提取秒数,然后将纳秒转换为毫秒.我愿意接受任何建议.
Part of the difficulty is I don't think there is a package like lubridate
to handle it. I'm not sure if I need to use a regular expression to extract the seconds and then transform the nanoseconds to milliseconds. I'm open to any suggestions.
此外,您如何建议处理 D
?我当时想我应该使用 gsub("D",-",df $ timestamp)
,然后像 lubridate
这样的包就可以解析时间戳了,甚至可以达到纳秒级的精度.?
Also, how do you recommend dealing with the D
? I was thinking I should use gsub("D", "-", df$timestamp)
and maybe then a package like lubridate
could parse the timestamp even with the nanosecond precision?
推荐答案
您可以在 gsub("D",",x)
之后使用 as.POSIXct
:
as.POSIXct(gsub("D", " ", "2019-03-02D00:00:12.214841000"))
此后,您仍然可以使用毫秒级精度:
You can still work with millisecond precision afterwards:
dt <- as.POSIXct(gsub("D", " ", "2019-03-02D00:00:12.214841000"))
dt
[1] "2019-03-02 00:00:12 CET"
for(i in 1:1000) dt <- dt - 0.001
dt
[1] "2019-03-02 00:00:11 CET"
如果要显示毫秒数,可以使用 format
:
If you want to display those milliseconds you can use format
:
format(dt, "%Y-%m-%d %H:%M:%OS3")
[1] "2019-03-02 00:00:11.214"
format(dt - 1E-3, "%Y-%m-%d %H:%M:%OS3")
[1] "2019-03-02 00:00:11.213"
format(dt - 10E-3, "%Y-%m-%d %H:%M:%OS3")
[1] "2019-03-02 00:00:11.204"
这篇关于R中的Delta时间戳解析(纳秒,微秒,毫秒)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!