Last active
November 5, 2022 11:59
-
-
Save kowalcj0/cee64e3eb91b9ffd46e33ca82edf057f to your computer and use it in GitHub Desktop.
Fix time format in SubRip srt subtitle files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import re, sys | |
from pathlib import Path | |
def fix_srt_time_format(sub_file_name: str): | |
"""Fix time format in SubRip srt subtitle files. | |
This script will: | |
* replace `.` delimiter between seconds and miliseconds with expected `,` | |
* replace leading `0:` in timestamps with expected `00:` | |
For reference please see: https://en.wikipedia.org/wiki/SubRip | |
""" | |
if not sub_file_name.endswith(".srt"): | |
return | |
file_path = Path(sub_file_name) | |
with open(file_path, "r") as sub_file_handle: | |
with open(f"{file_path.stem}.fixed.srt", "w", encoding="UTF-8") as fixed_sub_file_handle: | |
for line in sub_file_handle.readlines(): | |
if re.match(".*-->.*", line): | |
start, end = line.split(" --> ") | |
if "." in start: | |
start = re.sub("\.", ",", start) | |
end = re.sub("\.", ",", end) | |
if start.startswith("0:"): | |
start = re.sub("^0:", "00:", start) | |
end = re.sub("^0:", "00:", end) | |
new_line = f"{start} --> {end}" | |
fixed_sub_file_handle.write(new_line) | |
else: | |
fixed_sub_file_handle.write(line) | |
for file_name in sys.argv[1:]: | |
fix_srt_time_format(Path(file_name)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script can be executed as a standalone script or can be executed from Nautilus (Gnome's GUI file manager) by right-clicking on a subtitle file.
To make if available in Nautilus' righ-click menu, simply save this script in
/home/${USER}/.local/share/nautilus/scripts/
and make it executablechmod +x fixSrtTimeFormat.py
.