Skip to content

Instantly share code, notes, and snippets.

@lwrubel
Last active June 26, 2024 13:24
Show Gist options
  • Save lwrubel/0f7dc13940bf5a8072edfa94c1396739 to your computer and use it in GitHub Desktop.
Save lwrubel/0f7dc13940bf5a8072edfa94c1396739 to your computer and use it in GitHub Desktop.
Shift timestamps for captions in VTT files. Usage: python3 captions-shift.py my_captions.vtt my_edited_captions.vtt -2.25
#!/usr/bin/env python3
import webvtt
from datetime import datetime, timedelta
import argparse
parser = argparse.ArgumentParser(description="Shift caption start \
and end times in a .vtt file")
parser.add_argument("inputfile", help="input filename, must be VTT format")
parser.add_argument("outputfile", help="output filename")
parser.add_argument("seconds", type=float, help="number of seconds to \
shift caption times. Can be \
negative.")
args = parser.parse_args()
def adjust_time(timestamp, seconds):
t = datetime.strptime(timestamp, "%H:%M:%S.%f")
d = timedelta(seconds=seconds)
new_timestamp = t + d
return new_timestamp.strftime("%H:%M:%S.%f")
vtt = webvtt.read(args.inputfile)
for caption in vtt:
caption.start = adjust_time(caption.start, args.seconds)
caption.end = adjust_time(caption.end, args.seconds)
vtt.save(args.outputfile)
@lwrubel
Copy link
Author

lwrubel commented Sep 27, 2022

Glad it was useful to someone else!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment