How to convert time format to milliseconds and vice versa in Python?

The reason is because I am creating 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. The timeline may look like any of the following

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

This would be easier if many numbers were not optional. But since they are, I think I should use some kind of regular expression to parse it?

+4
source share
2 answers

From line to millisecond:

 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 milliseconds to a line:

 hours, milliseconds = divmod(miliseconds, 3600000) minutes, milliseconds = divmod(miliseconds, 60000) seconds = float(milliseconds) / 1000 s = "%i:%02i:%06.3f" % (hours, minutes, seconds) 
+10
source
 from time import time time_in_seconds = int(time()) time_in_miliseconds = int(time_in_seconds *1000) 

You can also use str (x) to convert x to string. From there, you can use various methods to create the desired line, for example: (both of them assume that you already have the hrs, min, sec, msec variables with the values โ€‹โ€‹you want)

 str(hrs) + ':' + str(min) + ':' + str(sec) + '.' + str(msec) 

or, more pythonically:

 '{hrs}:{min}:{sec}.{msec}'.format(hrs = str(hrs), min = str(min), sec = str(sec), msec = str(msec)) 

Alternatively, you can use the strftime () function in the time module if you want to use the current time. check out http://docs.python.org/library/time.html

-1
source

Source: https://habr.com/ru/post/1346460/


All Articles