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

时间:2018-03-08 01:28:44

标签: r datetime time posixct

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

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

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

我想将这个UTC时间格式转换为具有毫秒级别的美国CST时间。

我目前的代码是:

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

事实证明它真的搞砸了,结果是错误的。

非常感谢有人可以提供帮助。

2 个答案:

答案 0 :(得分:1)

这是我的方法

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“

答案 1 :(得分:1)

%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"