Reputation: 4120
How do I use strptime
or any other functions to parse time stamps with milliseconds in R?
time <- "2010-01-15 13:55:23.975"
print(time)
# [1] "2010-01-15 13:55:23.975"
strptime(time, format="%Y-%m-%d %H:%M:%S.%f")
# [1] NA
strptime(time, format="%Y-%m-%d %H:%M:%S")
# [1] "2010-01-15 13:55:23"`
Upvotes: 97
Views: 56317
Reputation: 33397
Another option to achive this, without the need to set options(digits.secs=3)
is using format()
:
format(Sys.time(), "%Y-%m-%d %H:%M:%OS3")
# alternative:
format(Sys.time(), digits = 3L)
time <- "2010-01-15 13:55:23.975"
# using strptime to convert the string
format(strptime(time, "%Y-%m-%d %H:%M:%OS"), "%Y-%m-%d %H:%M:%OS3")
format(strptime(time, "%Y-%m-%d %H:%M:%OS"), digits = 3L)
# using as.POSIXct to convert the string (under the hood also using strptime())
format(as.POSIXct(time), "%Y-%m-%d %H:%M:%OS3")
format(as.POSIXct(time), digits = 3L)
However, regarding as.POSIXct
please see this.
Upvotes: 1
Reputation:
You can also use strptime(time, "%OSn")
where 0 <= n <= 6, without having to set digits.secs
.
The documentation states "Which of these are supported is OS-dependent." so YMMV.
Upvotes: 31
Reputation: 18864
Courtesy of the ?strptime
help file (with the example changed to your value):
> z <- strptime("2010-01-15 13:55:23.975", "%Y-%m-%d %H:%M:%OS")
> z # prints without fractional seconds
[1] "2010-01-15 13:55:23 UTC"
> op <- options(digits.secs=3)
> z
[1] "2010-01-15 13:55:23.975 UTC"
> options(op) #reset options
Upvotes: 137