Skip to content

Instantly share code, notes, and snippets.

@chanux
Created March 15, 2012 07:11
Show Gist options
  • Save chanux/2042676 to your computer and use it in GitHub Desktop.
Save chanux/2042676 to your computer and use it in GitHub Desktop.
A simple python tool to fix time of srt files
#!/usr/bin/env python
from sys import argv, exit
from os import path
import datetime
if len(argv) == 5:
(script, inputf, outputf, sign, msec) = argv
else:
print "fixsrt <input.srt> <output.srt> <+/-> <milli seconds>"
exit(1)
def fixline(line, sign, msec):
times = line.split(' --> ')
tformat = '%H:%M:%S,%f'
times[0] = datetime.datetime.strptime(times[0], tformat)
times[1] = datetime.datetime.strptime(times[1], tformat)
if sign == '+':
a = times[0] + datetime.timedelta(milliseconds=msec)
b = times[1] + datetime.timedelta(milliseconds=msec)
elif sign == '-':
a = times[0] - datetime.timedelta(milliseconds=msec)
b = times[1] - datetime.timedelta(milliseconds=msec)
a = a.time().strftime("%H:%M:%S,%f")[:12]
b = b.time().strftime("%H:%M:%S,%f")[:12]
return '%s --> %s' % (a, b)
if not path.isfile(inputf) and not inputf.endswith('.srt'):
print "Invalid input file: %s" % inputf
exit(1)
elif not msec.isdigit() and not len(msec) <= 4:
print "Invalid time: %s. Pass a numeric value up to 4 digits" % msec
exit(1)
elif not sign == "+" and not sign == "-":
print "Invalid Sign: '%s'. Use + or -" % sign
exit(1)
outf = open(outputf, 'w')
for line in open(inputf, 'r'):
if '-->' in line:
line = fixline(line.rstrip(), sign, int(msec))
print >> outf, line
else:
outf.write(line)
outf.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment