Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions youtube_transcript_api/formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,10 @@ def _seconds_to_timestamp(self, time: float) -> str:
>>> self._seconds_to_timestamp(6.93)
'00:00:06.930'
"""
time = float(time)
hours_float, remainder = divmod(time, 3600)
mins_float, secs_float = divmod(remainder, 60)
hours, mins, secs = int(hours_float), int(mins_float), int(secs_float)
ms = int(round((time - int(time)) * 1000, 2))
milliseconds = round(float(time) * 1000)
total_secs, ms = divmod(milliseconds, 1000)
total_mins, secs = divmod(total_secs, 60)
hours, mins = divmod(total_mins, 60)
return self._format_timestamp(hours, mins, secs, ms)

def format_transcript(self, transcript: FetchedTranscript, **kwargs) -> str:
Expand Down
18 changes: 18 additions & 0 deletions youtube_transcript_api/test/test_formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,24 @@ def test_srt_formatter_starting(self):
self.assertEqual(lines[0], "1")
self.assertEqual(lines[1], "00:00:00,000 --> 00:00:01,500")

def test_srt_formatter_carries_rounded_milliseconds(self):
transcript = FetchedTranscript(
snippets=[
FetchedTranscriptSnippet(
text="Rounded boundary", start=1.9996, duration=1.0
),
],
language="English",
language_code="en",
is_generated=True,
video_id="12345",
)

content = SRTFormatter().format_transcript(transcript)
lines = content.split("\n")

self.assertEqual(lines[1], "00:00:02,000 --> 00:00:03,000")

def test_srt_formatter_middle(self):
content = SRTFormatter().format_transcript(self.transcript)
lines = content.split("\n")
Expand Down