Reputation: 81
I want to extract the timestamp from a string, but the milliseconds part is not being read properly
datetime.strptime('20130629110924095','%Y%m%d%H%M%S%f')
produces the following output
datetime.datetime(2013, 6, 29, 11, 9, 24, 95000)
instead of
datetime.datetime(2013, 6, 29, 11, 9, 24, 95)
to be clear: 95 milliseconds
What am I doing wrong?
Upvotes: 5
Views: 2480
Reputation: 414139
95000
is in microseconds that is equivalent to 95 milliseconds i.e., the input ('095'
) is already correct if you want to get 95 milliseconds.
Here's the same input with some additional formatting for readability:
>>> from datetime import datetime
>>> datetime.strptime('2013-06-29 11:09:24.095','%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 6, 29, 11, 9, 24, 95000)
A millisecond is 0.001
seconds and therefore 95
milliseconds is 0.095
seconds that is why 095
is the correct input for %f
that parses the fractional part of a second.
Upvotes: 1
Reputation: 3027
Microseconds consist of six digits. 95 milliseconds = 95000 microseconds.
So to get datetime with 95 milliseconds like datetime.datetime(2013, 6, 29, 11, 9, 24, 95000)
write:
datetime.strptime('20130629110924095000','%Y%m%d%H%M%S%f')
Upvotes: 2
Reputation: 8831
The documentation says:
%f is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available). When used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right.
So the result you get is expected behaviour, your '095' is padded to '095000'.
Upvotes: 2