Skip to content

Instantly share code, notes, and snippets.

@dbalduini
Last active October 6, 2019 18:16
Show Gist options
  • Save dbalduini/d8c2570fda36f2617a53b1609311242f to your computer and use it in GitHub Desktop.
Save dbalduini/d8c2570fda36f2617a53b1609311242f to your computer and use it in GitHub Desktop.
Add or Remove delay to some SubRip file format (.srt).
#!/usr/bin/python
"""
fix_sub_delay.py:
Add or Remove delay to some SubRip file format (.srt).
@author [email protected]
"""
import sys
import os
import re
from datetime import datetime, timedelta
if len(sys.argv) < 3:
print('Expected args <millis to sum> <path to file>')
sys.exit(1)
ts_pattern = '%H:%M:%S,%f'
millis_to_sum = sys.argv[1]
filename = sys.argv[2]
file_dir = os.path.dirname(os.path.abspath(filename))
def parse_time(s):
return datetime.strptime(s.strip(), ts_pattern)
def add_millis(date):
time = parse_time(date)
time = time + timedelta(milliseconds=int(millis_to_sum))
return time.strftime(ts_pattern)
def add_timestamp(ts):
begin, end = [add_millis(x) for x in ts.split('-->')]
# remove the last three numbers of the timestamp
return begin[:-3] + ' --> ' + end[:-3]
def main():
counter = 1
timestamp = False
f = open(filename, 'r')
output = open(os.path.join(file_dir, 'output.srt'), 'w')
for line in f:
print(counter, 'line', repr(line))
if timestamp:
new_line = add_timestamp(line)
output.write(new_line + '\n')
else:
output.write(line)
# Check if the next line will be a timestamp
regex = "^%s\\s+$" % (counter)
pattern = re.compile(regex)
if pattern.match(line):
counter += 1
timestamp = True
else:
timestamp = False
# Close resources
f.close()
output.close()
print('Total parsed lines: ', counter-1)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment