Skip to content

Instantly share code, notes, and snippets.

@xavierskip
Created July 22, 2018 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xavierskip/4ab6f8d1591d321419763a0948e47599 to your computer and use it in GitHub Desktop.
Save xavierskip/4ab6f8d1591d321419763a0948e47599 to your computer and use it in GitHub Desktop.
vtt to srt
#!/usr/bin/env python
from datetime import datetime, timedelta
filename = 'input.vtt'
srt = []
delta = -10 # Subtitle timeline
count = 1
timeline = 0
def changetime(time, delta):
'''
delta is seconds
'''
if delta == 0:
return time
timelineformat = "%H:%M:%S.%f"
t1 = datetime.strptime(time, timelineformat)
t2 = t1 + timedelta(seconds=delta)
return t2.strftime(timelineformat)[:-3]
with open(filename, 'r') as f:
while True:
l = f.readline()
if l == '':
break
if timeline:
try:
t1,t2 = l.strip().split(' --> ')
except Exception as e:
print(l)
raise e
t1 = changetime(t1, delta)
t2 = changetime(t2, delta)
l = '{}\n'.format(' --> '.join([t1, t2]))
timeline = 0
if l == '\n':
l = '\n{}\n'.format(count)
count += 1
timeline = 1
srt.append(l)
with open('output.srt','w') as f:
f.writelines(srt)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment