Python, strptime skips zeros in millisecond section

I want to extract the timestamp from a string, but part of the milliseconds is not being read correctly

datetime.strptime('20130629110924095','%Y%m%d%H%M%S%f')

      

outputs the following output

datetime.datetime(2013, 6, 29, 11, 9, 24, 95000)

      

instead

datetime.datetime(2013, 6, 29, 11, 9, 24, 95)

      

to be clear: 95 milliseconds

What am I doing wrong?

+3


source to share


3 answers


Microseconds are six digits long. 95 milliseconds = 95000 microseconds. So, to get a 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')

      

+1


source


The documentation says:

% f is an extension of the format character set in the C standard (but implemented separately in datetime objects and therefore always available). When used with the strptime () method, the% f directive accepts one to six digits and zero pads to the right.



So the result you get is what you expect, your "095" is complemented by "095000".

+1


source


95000

is in microseconds, which is equivalent to 95 milliseconds, meaning input ( '095'

) is already correct if you want 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 are 0.095

seconds, so 095

is the correct input for %f

, which parses the fractional part of a second.

0


source







All Articles