Reputation: 309
I have a full list of time stamps, named 'time'.
typeof(time) is character, time[1:5] is
c('20151122224357714','20151122225351332' , '20151122230112066', '20151122231644405', '20151122233024263')
I want to convert this UTC time format to U.S. CST time with the millisecond level.
My current code is:
timeDate(time[1:5], format = "%Y%m%d%H:%M:%OS", FinCenter = America/Chicago")
It turned out to be really messed up, and the results are wrong.
Thank you so much if someone could help.
Upvotes: 1
Views: 702
Reputation: 93938
The %OS
input format expects a decimal place, so add one in then check what you get:
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"
Upvotes: 1
Reputation: 2246
here is my approach
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"
Upvotes: 1