如何在Python中将时间格式转换成毫秒? [英] How to convert time format into milliseconds and back in Python?

查看:3149
本文介绍了如何在Python中将时间格式转换成毫秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原因是因为我正在使用ffmpeg的脚本,我需要能够以00:00:00 [.000]格式添加/减少时间。



最后3位数字是可选的,它们表示毫秒。时间字符串可能看起来像以下任何一种

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

如果很多位数不是,这将会更容易可选的。但是由于它们是,我想我必须使用某种正则表达式来解析它?

解决方案

从字符串到毫秒:

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

从毫秒到字符串:

  hours,milliseconds = divmod(miliseconds,3600000)
minutes,milliseconds = divmod(miliseconds,60000)
秒= float(毫秒)/ 1000
s =%i:%02i:%06.3f%(小时,分钟,秒)


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?

解决方案

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)

这篇关于如何在Python中将时间格式转换成毫秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆