Reputation: 320
Given a data set "eur_usd" of class data.frame:
pair dt bid ask
1 EUR/USD 20180401 21:02:24.820 1.23178 1.23286
2 EUR/USD 20180401 21:02:25.304 1.23156 1.23285
3 EUR/USD 20180401 21:02:25.358 1.23155 1.23285
and with
> class(eur_usd$dt)
[1] "character"
I can't coerce $dt to POSIXct - everything is just NA:
strptime(eur_usd$dt, "%Y%m%d %H:%M:%S.%f")
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[36] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
as.POSIXct(eur_usd$dt, format = "%Y%m%d %H:%M:%S.%f", tz = "GMT")
[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
Am I doing something wrong?
Upvotes: 0
Views: 116
Reputation: 368241
@Rich showed you how to correctly specify the required format when you use a converter requiring a format.
Alternatively, you could use the anytime package which does not need a format specififier (but heuristically tries a number of plausible alternatives):
R> anytime::anytime(c("20180401 21:02:24.820", "20180401 21:02:25.304",
+ "20180401 21:02:25.358"))
[1] "2018-04-01 21:02:24.819 CDT" "2018-04-01 21:02:25.303 CDT"
[3] "2018-04-01 21:02:25.358 CDT"
R>
Upvotes: 1
Reputation: 99331
You should use %OS
for milliseconds
as.POSIXct(df$dt, format = "%Y%m%d %H:%M:%OS")
# [1] "2018-04-01 21:02:24 PDT" "2018-04-01 21:02:25 PDT"
# [3] "2018-04-01 21:02:25 PDT"
Upvotes: 2