95

How do I use strptime or any other functions to parse time stamps with milliseconds in R?

time[1]
# [1] "2010-01-15 13:55:23.975"
strptime(time[1], format="%Y-%m-%d %H:%M:%S.%f")
# [1] NA
strptime(time[1], format="%Y-%m-%d %H:%M:%S")
# [1] "2010-01-15 13:55:23"`
MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
signalseeker
  • 4,100
  • 7
  • 30
  • 36

2 Answers2

133

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
Ken Williams
  • 22,756
  • 10
  • 85
  • 147
Aniko
  • 18,516
  • 4
  • 48
  • 45
  • Thanks, I missed that in the strptime doc. I was looking for a format character and gave up when I did not see one. – signalseeker Jan 27 '10 at 21:30
  • 3
    so would I! The "%OS" bit is awesome. – Pierre D Jan 16 '13 at 22:22
  • 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 "", line 1, in 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' – firebush Nov 14 '15 at 21:58
  • 2
    @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. – IRTFM Apr 25 '16 at 16:15
  • Is it possible to print milliseconds in the output of `system.time`? – Julien Oct 03 '22 at 16:15
30

You can also use strptime(time[1], "%OSn") where 0 <= n <= 6, without having to set digits.secs.

The documentation states "Which of these are supported is OS-dependent." so YMMV.