quick-scripts/subs-helper.py

53 lines
1.3 KiB
Python

# A snippet to calculate difference between two srt timestamps
def str2msecs(timestr: str) -> int:
"""
Convert srt timestamp to a millisecond int value
>>> str2msecs("00:00:00,052")
52
"""
hrs_str, mins_str, rem = timestr.split(":")
secs_str, msecs_str = rem.split(",")
hrs, mins = int(hrs_str), int(mins_str)
secs, msecs = int(secs_str), int(msecs_str)
rv = hrs*3600 + mins*60 + secs
return rv*1000 + msecs
def msecs2str(msecs: float) -> str:
"""
Convert a millisecond int value to srt timestamp
>>> msecs2str(52)
'00:00:00,052'
>>> msecs2str(52.488)
'00:00:00,052'
"""
hrs, rem = divmod(msecs, 3600000)
mins, rem = divmod(rem, 60000)
secs, msecs = divmod(rem, 1000)
hrs, mins, secs, msecs = int(hrs), int(mins), int(secs), int(msecs)
# https://docs.python.org/3/library/string.html#format-specification-mini-language
return f"{hrs:02d}:{mins:02d}:{secs:02d},{msecs:03d}"
def foo(s1: str, s2: str) -> float:
"""
Take 2 timestamps and find difference between them
ie,
foo(s1, s2) = s1 - s2
>>> foo("00:00:59,128", "00:00:06,640")
52.488
"""
a = str2msecs(s1)
b = str2msecs(s2)
#return msecs2str(a-b)
return (a-b) / 1000
a = foo("00:00:59,128", "00:00:06,640")
# 52.488
print(a)
print(msecs2str(a))