Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert time format into milliseconds and back in Python?

The reason is because I'm making a script to work with ffmpeg and I need to be able to add/subtract time in the format 00:00:00[.000]

The last 3 digits are optional and they mean milliseconds. A time string could look like any of the following

4:34.234
5.000
2:99:34
4:14

This would be easier if a lot of the digits weren't optional. But since they are, I'm thinking I have to use some sort of regex to parse it?

like image 254
fent Avatar asked Apr 03 '11 17:04

fent


People also ask

How do I convert time to milliseconds Python?

How do you convert datetime to milliseconds? A simple solution is to get the timedelta object by finding the difference of the given datetime with Epoch time, i.e., midnight 1 January 1970. To obtain time in milliseconds, you can use the timedelta. total_seconds() * 1000 .

How do you convert timestamps to milliseconds?

Multiply the timestamp of the datetime object by 1000 to convert it to milliseconds.


1 Answers

From string to milliseconds:

s = "4:34.234"
hours, minutes, seconds = (["0", "0"] + s.split(":"))[-3:]
hours = int(hours)
minutes = int(minutes)
seconds = float(seconds)
miliseconds = int(3600000 * hours + 60000 * minutes + 1000 * seconds)

From milliseonds to string:

hours, milliseconds = divmod(miliseconds, 3600000)
minutes, milliseconds = divmod(miliseconds, 60000)
seconds = float(milliseconds) / 1000
s = "%i:%02i:%06.3f" % (hours, minutes, seconds)
like image 138
Sven Marnach Avatar answered Sep 16 '22 13:09

Sven Marnach