[refactor] duration strings: move parsing logic to utils.py

This commit is contained in:
Bnyro 2025-03-20 21:16:37 +01:00 committed by Markus Heiser
parent c28d35c7fc
commit 4dfc47584d
5 changed files with 42 additions and 42 deletions

View file

@ -1,7 +1,5 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Utility functions for the engines
"""
"""Utility functions for the engines"""
from __future__ import annotations
@ -18,6 +16,7 @@ from random import choice
from html.parser import HTMLParser
from html import escape
from urllib.parse import urljoin, urlparse, parse_qs, urlencode
from datetime import timedelta
from markdown_it import MarkdownIt
from lxml import html
@ -831,3 +830,25 @@ def js_variable_to_python(js_variable):
s = s.replace(chr(1), ':')
# load the JSON and return the result
return json.loads(s)
def parse_duration_string(duration_str: str) -> timedelta | None:
"""Parse a time string in format MM:SS or HH:MM:SS and convert it to a `timedelta` object.
Returns None if the provided string doesn't match any of the formats.
"""
duration_str = duration_str.strip()
if not duration_str:
return None
try:
# prepending ["00"] here inits hours to 0 if they are not provided
time_parts = (["00"] + duration_str.split(":"))[:3]
hours, minutes, seconds = map(int, time_parts)
return timedelta(hours=hours, minutes=minutes, seconds=seconds)
except (ValueError, TypeError):
pass
return None