Skip to content
Advertisement

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

I am able to parse strings containing date/time with time.strptime

JavaScript

How can I parse a time string that contains milliseconds?

JavaScript

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

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

JavaScript

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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement