How can I parse a time string containing milliseconds in it with python?

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.

time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')

However, time.struct_time doesn’t actually store milliseconds/microseconds. You’re better off using datetime, like this:

>>> from datetime import datetime
>>> a = datetime.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
>>> a.microsecond
123000

As you can see, .123 is correctly interpreted as 123 000 microseconds.

Leave a Comment