myYouTube/backend/app/core/duration.py

23 lines
643 B
Python
Raw Normal View History

import re
_ISO8601_DURATION_RE = re.compile(
r"P(?:(?P<days>\d+)D)?"
r"(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?"
)
def parse_iso8601_duration(value: str | None) -> int | None:
if not value:
return None
match = _ISO8601_DURATION_RE.fullmatch(value)
if not match:
return None
parts = match.groupdict()
if not any(parts.values()):
return None
days = int(parts["days"] or 0)
hours = int(parts["hours"] or 0)
minutes = int(parts["minutes"] or 0)
seconds = int(parts["seconds"] or 0)
return days * 86400 + hours * 3600 + minutes * 60 + seconds