将字符转换为r中毫秒级别的时间对象

convert character into a time object with millisecond level in r

我有一个完整的时间戳列表,名为 'time'。

typeof(time)是字符,time[1:5]是

c('20151122224357714','20151122225351332' , '20151122230112066', '20151122231644405', '20151122233024263')

我想将此 UTC 时间格式转换为 U.S。毫秒级CST时间

我当前的代码是:

 timeDate(time[1:5], format = "%Y%m%d%H:%M:%OS", FinCenter = America/Chicago")

原来是真的乱七八糟,结果不对

如果有人能提供帮助,非常感谢。

这是我的方法

library(lubridate)
test <- c('20151122224357714','20151122225351332' , '20151122230112066', '20151122231644405', '20151122233024263')
time <- as.POSIXct(test, format = "%Y%m%d%H%M%S", tz = "America/Chicago")
millis <- substr(test, 15, 17)
options(digits.secs = 3)
result <- time+milliseconds(as.numeric(millis))

result

"2015-11-22 22:43:57.713 CST" "2015-11-22 22:53:51.332 CST" "2015-11-22 23:01:12.065 CST" “2015-11-22 23:16:44.404 CST” “2015-11-22 23:30:24.263 CST”

%OS 输入格式需要一个小数位,所以加一个然后检查你得到什么:

x <- c('20151122224357714','20151122225351332',
       '20151122230112066', '20151122231644405', '20151122233024263')

out <- as.POSIXct(sub("^(\d{14})", "\1.", x), format="%Y%m%d%H%M%OS", tz="UTC")

# check that the milliseconds are there:
format(out, "%F %H:%M:%OS3")
#[1] "2015-11-22 22:43:57.713" "2015-11-22 22:53:51.332"
#[3] "2015-11-22 23:01:12.065" "2015-11-22 23:16:44.404"
#[5] "2015-11-22 23:30:24.263"

# note that the rounding is funny when printed due to floating point precision,
# but the data is exact
dput(out)
#structure(c(1448232237.714, 1448232831.332, 1448233272.066, 1448234204.405, 
#1448235024.263), class = c("POSIXct", "POSIXt"), tzone = "UTC"