I am able to parse strings containing date/time with time.strptime
JavaScript
x
4
1
>>> import time
2
>>> time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S')
3
(2009, 3, 30, 16, 31, 32, 0, 89, -1)
4
How can I parse a time string that contains milliseconds?
JavaScript
1
7
1
>>> time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S')
2
Traceback (most recent call last):
3
File "<stdin>", line 1, in <module>
4
File "/usr/lib/python2.5/_strptime.py", line 333, in strptime
5
data_string[found.end():])
6
ValueError: unconverted data remains: .123
7
Advertisement
Answer
Python 2.6 added a new strftime/strptime macro %f
. The docs are a bit misleading as they only mention microseconds, but %f
actually parses any decimal fraction of seconds with up to 6 digits, meaning it also works for milliseconds or even centiseconds or deciseconds.
JavaScript
1
2
1
time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
2
However, time.struct_time doesn’t actually store milliseconds/microseconds. You’re better off using datetime
, like this:
JavaScript
1
5
1
>>> from datetime import datetime
2
>>> a = datetime.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
3
>>> a.microsecond
4
123000
5
As you can see, .123
is correctly interpreted as 123 000
microseconds.