【问题标题】:pysrt: get time in millisecondspysrt:以毫秒为单位获取时间
【发布时间】:2019-04-01 19:35:13
【问题描述】:

我想以毫秒为单位获取字幕文件的开始和结束时间:

SIMPLE_FILE = """
1
00:00:03,010 --> 00:00:33,400
cette matrice-là <i>E<sub>t</sub>·…·E<sub>1</sub>A</i> possède une ligne

2
00:01:00,000 --> 00:02:31,020
there was a SubRip file
with two subtitles.
"""
with open("subtitles.srt", "w", encoding="utf-8") as fp:fp.write(SIMPLE_FILE)

我使用pysrt加载字幕文件:

import pysrt
sub = pysrt.open("subtitles.srt")
# Start and End time
start = sub[0].start.to_time()
end = sub[0].end.to_time()

print(start)
print(end)

00:00:03.010000

00:00:33.400000

如您所见,我得到了 Hour:Minutes:Seconds.Millisecond 格式。现在,我的问题是:如何将其转换为毫秒?

编辑

我检查了类型:

type(start)

日期时间.时间

编辑 2

基于Converting string to datetime in Python using strptime

我试过了:

from datetime import datetime

dt_obj = datetime.strptime(str(start),
                           '%H:%M:%S.%f')
millisec = dt_obj.timestamp() * 1000

print(millisec)

我明白了:


OSError Traceback(最近调用 最后)在() 3 dt_obj = datetime.strptime(str(start), 4 '%H:%M:%S.%f') ----> 5 毫秒 = dt_obj.timestamp() * 1000 6 7 次打印(毫秒)

OSError: [Errno 22] 无效参数

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您不需要解析start,因为它已经是一个time 对象。只需访问其属性。见datetime.time specs

    您应该可以访问:

    start.hour
    start.minute
    start.second
    start.microsecond
    

    【讨论】:

    • 所以,我会这样做:milliseconds = start.hour*3600000 + start.minute*60000 + start.second*1000 + start.microsecond*0.001,对吧?
    • @henry 是的,我会这样做,或者((start.hour * 60 + start.minute) * 60 + start.second) * 1000 + start.microsecond
    • 快速提问:为什么只添加微秒?不是必须是 0.001*microseconds 才能获得毫秒吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-26
    • 2017-08-05
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-25
    相关资源
    最近更新 更多