Python:如何将字符串时间转换为十进制秒?

时间:2021-05-15 08:10:18

标签: python python-3.x string python-datetime

String Time 
00:51:21,920

Decimal Time
3,081.92 (second)

无论如何可以在字符串时间和十进制时间之间转换(以秒为单位)?我想在moviepy VideoFileClip.subclip 中使用它。

以下是我所做的并且有效。但我认为应该有更简单的方法,比如库中的函数。

def TrsTime(VideoTime):
  return (datetime.strptime(VideoTime, '%H:%M:%S,%f').hour*60*60+
  datetime.strptime(VideoTime, '%H:%M:%S,%f').minute*60+
  datetime.strptime(VideoTime, '%H:%M:%S,%f').second+
  datetime.strptime(VideoTime, '%H:%M:%S,%f').microsecond/1000/1000)

1 个答案:

答案 0 :(得分:0)

是的,有一个更简单的方法:

from datetime import datetime as dt

(dt.strptime(VideoTime, '%H:%M:%S,%f') - dt(1900, 1, 1)).total_seconds()

>>> 3081.92

这适用于 timedelta 对象具有 .total_seconds() 函数的主体。因此,通过从 1900 年 1 月 1 日减去您的时间(其年、月、日默认为 1900 年 1 月 1 日),您将获得以秒为单位的增量。

相关问题