--- /dev/null
+#!/usr/bin/python
+
+# Copyright (C) 2012 Jorge Gorbe Moya <jgorbe@slackito.com>
+#
+# This program is free software. It comes without any warranty, to
+# the extent permitted by applicable law. You can redistribute it
+# and/or modify it under the terms of the Do What The Fuck You Want
+# To Public License, Version 2, as published by Sam Hocevar. See
+# http://sam.zoy.org/wtfpl/COPYING for more details
+
+# Quick and dirty SRT subtitle timestamp shifting tool.
+#
+# usage: srtshift <infile> <outfile> <offset-in-seconds>
+
+import sys
+
+# possible exceptions
+class SubtitleFormatError:
+ pass
+
+# a SRT timestamp class, convertible to and from string, with a shifting(add) method
+class Timestamp:
+ def __init__(self, h, m, s, ms):
+ self.hours = h
+ self.minutes = m
+ self.secs = s
+ self.ms = ms
+
+ def addSeconds(self, seconds):
+ offset_ms = int(seconds*1000)
+ # add offset to self.ms
+ ms = self.ms + offset_ms
+ # propagate to seconds
+ secs = self.secs + ms / 1000
+ ms = ms % 1000
+ #propagate to minutes
+ minutes = self.minutes + secs / 60
+ secs = secs % 60
+ #propagate to hours
+ hours = self.hours + minutes / 60
+ minutes = minutes % 60
+ # if result is negative, it will have been propagated to the hours component
+ if hours < 0:
+ return Timestamp(0,0,0,0)
+ else:
+ return Timestamp(hours, minutes, secs, ms)
+
+
+ def __str__(self):
+ return "%02d:%02d:%02d,%03d"%(self.hours, self.minutes, self.secs, self.ms)
+
+ @classmethod
+ def fromString(cls, s):
+ items = s.split(":")
+ items[2:] = items[2].split(",")
+ hours = int(items[0])
+ minutes = int(items[1])
+ secs = int(items[2])
+ ms = int(items[3])
+ return cls(hours, minutes, secs, ms)
+
+################
+# MAIN PROGRAM #
+################
+infile = open(sys.argv[1])
+outfile = open(sys.argv[2], "w")
+offset = float(sys.argv[3])
+
+subtitle_counter = 1
+
+try:
+ while True:
+ # copy subtitle number to output, check if they are consecutive
+ line = infile.next()
+ subtitle_number_from_file = int(line)
+ if subtitle_counter != subtitle_number_from_file: raise SubtitleFormatError
+ subtitle_counter += 1
+ outfile.write(line)
+
+ # parse start and end times, shift them, write to output
+ line = infile.next()
+ s1, arrow, s2 = line.split()
+ if arrow != "-->": raise SubtitleFormatError
+ t1 = Timestamp.fromString(s1).addSeconds(offset)
+ t2 = Timestamp.fromString(s2).addSeconds(offset)
+ outfile.write("%s --> %s\n"%(str(t1), str(t2)))
+
+ # copy lines to output until next subtitle (after blank line)
+ line = infile.next()
+ while line.strip() != "":
+ outfile.write(line)
+ line = infile.next()
+ outfile.write("\n")
+
+except StopIteration:
+ pass
+
+infile.close()
+outfile.close()
+
+