Калькулятор продолжительности времени

Прибавляйте или вычитайте часы, минуты и секунды для расчёта временных интервалов.

Часто задаваемые вопросы

Реализация кода

import re

def parse_duration(s: str) -> int:
    """Parse a duration string like '1h 30m 45s' into total seconds."""
    pattern = r'(?:(d+)s*dw*)?s*(?:(d+)s*hw*)?s*(?:(d+)s*mw*)?s*(?:(d+)s*sw*)?'
    match = re.fullmatch(pattern.strip(), s.strip(), re.IGNORECASE)
    if not match or not any(match.groups()):
        raise ValueError(f"Cannot parse duration: {s!r}")
    d, h, m, sec = (int(x or 0) for x in match.groups())
    return d * 86400 + h * 3600 + m * 60 + sec

def format_duration(seconds: int) -> str:
    """Format total seconds back to a human-readable string."""
    seconds = abs(int(seconds))
    d = seconds // 86400
    h = (seconds % 86400) // 3600
    m = (seconds % 3600) // 60
    s = seconds % 60
    parts = []
    if d: parts.append(f"{d}d")
    if h: parts.append(f"{h}h")
    if m: parts.append(f"{m}m")
    if s or not parts: parts.append(f"{s}s")
    return " ".join(parts)

def add_durations(*durations: str) -> str:
    total = sum(parse_duration(d) for d in durations)
    return format_duration(total)

# Examples
print(parse_duration("1h 30m"))       # 5400
print(parse_duration("2d 4h 15m 0s")) # 187500
print(format_duration(5400))          # "1h 30m"
print(add_durations("1h 30m", "45m", "2h 15m"))  # "4h 30m"

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.