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

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

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?

回答1:

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) 


回答2:

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 a string. From there you can use various methods to create the string you want, such as: (both of these assume you already have the variables hrs, min, sec, msec 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)) 

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!