5

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?

tokyoCoder
  • 81
  • 8
  • I tried padding with zeros, but it does not help datetime.strptime('20130629110924.095000','%Y%m%d%H%M%S.%f') – tokyoCoder Jun 24 '15 at 12:35
  • 2
    `%f` parses microseconds. 95000 microseconds equals 95 milliseconds. So `strptime` is already parsing your string correctly. – unutbu Jun 24 '15 at 13:10
  • I'm sorry. The error happened when I edited the file in MS Excel. It removed all trailing zeros from the source file! Did not see that coming! – tokyoCoder Jun 24 '15 at 13:28

3 Answers3

2

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')
Delimitry
  • 2,987
  • 4
  • 30
  • 39
  • Thank you for the answer, but the first code also outputs datetime.datetime(2013, 6, 29, 11, 9, 24, 9500) The answer I'm expecting is datetime.datetime(2013, 6, 29, 11, 9, 24, 95) I'll correct in the question regarding the second snippet – tokyoCoder Jun 24 '15 at 13:01
  • I see. But, datetime.strptime('20130629110924000095','%Y%m%d%H%M%S%f') gives me 95 microseconds, instead of 95 milliseconds. – tokyoCoder Jun 24 '15 at 13:17
  • Solved! Thanks, the issue was in the source file! – tokyoCoder Jun 24 '15 at 13:29
2

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'.

Bernhard
  • 8,583
  • 4
  • 41
  • 42
  • Thanks! So, what should I input to get 95 milliseconds as output? The data is read from a file in which this is written in the format "20130629 1109240 095" "20130629 1109240 195" etc. – tokyoCoder Jun 24 '15 at 13:05
1

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.

jfs
  • 399,953
  • 195
  • 994
  • 1,670