pysubs2

1.8.1 · active · verified Wed Apr 15

pysubs2 is an actively maintained Python library (current version 1.8.1) for editing subtitle files. It supports various formats including SubStation Alpha (ASS/SSA), SubRip (SRT), MicroDVD, MPL2, TMP, WebVTT, TTML, SAMI, and OpenAI Whisper captions. It offers both an API for programmatic manipulation and a small CLI tool for batch conversion and retiming. The library is typically released as new features are added or bugs are fixed, without a strict time-based cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a subtitle file, add a new event, shift all event timings, modify an existing event's text, and save the result in a different format (ASS). It highlights the use of `pysubs2.load`, `pysubs2.SSAEvent`, `pysubs2.make_time`, and `subs.save` methods.

import pysubs2
import os

# Create a dummy SRT file for demonstration
dummy_srt_content = """
1
00:00:01,000 --> 00:00:03,000
Hello, world!

2
00:00:04,000 --> 00:00:06,000
This is a test subtitle.
"""
with open("input.srt", "w", encoding="utf-8") as f:
    f.write(dummy_srt_content)

# Load the subtitle file
subs = pysubs2.load("input.srt", encoding="utf-8")
print(f"Loaded {len(subs)} subtitles.")

# Add a new subtitle event
subs.append(pysubs2.SSAEvent(
    start=pysubs2.make_time(s=7),
    end=pysubs2.make_time(s=9, ms=500),
    text="A new subtitle added via pysubs2."
))

# Shift all subtitles by 1.5 seconds forward
subs.shift(s=1, ms=500)

# Modify an existing subtitle
if len(subs) > 0:
    subs[0].text = "(Modified) " + subs[0].text

# Save the modified subtitles to a new ASS file
output_filename = "output_modified.ass"
subs.save(output_filename, format_="ass", encoding="utf-8")
print(f"Modified subtitles saved to {output_filename}.")

# Clean up dummy files
os.remove("input.srt")
os.remove(output_filename)

view raw JSON →