How to parse milliseconds?
Asked Answered
F

3

97

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"`
Fineman answered 27/1, 2010 at 20:48 Comment(0)
H
136

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
Heredia answered 27/1, 2010 at 20:55 Comment(5)
Thanks, I missed that in the strptime doc. I was looking for a format character and gave up when I did not see one.Fineman
so would I! The "%OS" bit is awesome.Renoir
Is this only in python3 or something? In my python2.7.8: >>> time.strptime(t, "%Y-%m-%d %H:%M:%OS") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/pythons/2.7.8/lib/python2.7/_strptime.py", line 467, in _strptime_time return _strptime(data_string, format)[0] File "/opt/pythons/2.7.8/lib/python2.7/_strptime.py", line 317, in _strptime (bad_directive, format)) ValueError: 'O' is a bad directive in format '%Y-%m-%d %H:%M:%OS'Stamm
@firebush: It's in R. It might require "%Y-%m-%d %H:%M:%OS3" on some platforms. The implementation of the "OS" format is labeled as OS-specific on the help pages.Delectable
Is it possible to print milliseconds in the output of system.time?Thankyou
M
31

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.

Meniscus answered 27/1, 2010 at 21:24 Comment(1)
This did not work for me too on the Ubuntu. That's yields NA .Utrecht
C
1

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.

Cerys answered 27/10, 2023 at 10:10 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.