Skip to content

parse_time

Class info

🛈 DocStrings

Time period parsing for CLI and API interfaces.

parse_time_period

parse_time_period(period: str) -> timedelta

Parse a time expression into a timedelta.

Examples:

  • Simple format: 1h, 2d, 1w
  • Full words: 1 hour, 2 days, 1 week
  • Combined: 1 week 2 days 3 hours
  • With separators: 1h, 30m
  • Signed: -1h, +2d
  • Decimal values: 1.5h

Parameters:

Name Type Description Default
period str

Time period string to parse

required

Raises:

Type Description
ValueError

If the time format is invalid

Returns:

Type Description
timedelta

Parsed time period as timedelta

Source code in src/llmling_agent/utils/parse_time.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def parse_time_period(period: str) -> timedelta:
    """Parse a time expression into a timedelta.

    Examples:
        - Simple format: 1h, 2d, 1w
        - Full words: 1 hour, 2 days, 1 week
        - Combined: 1 week 2 days 3 hours
        - With separators: 1h, 30m
        - Signed: -1h, +2d
        - Decimal values: 1.5h

    Args:
        period: Time period string to parse

    Raises:
        ValueError: If the time format is invalid

    Returns:
        Parsed time period as timedelta
    """
    # Handle sign
    sign_match = _SIGN_PATTERN.match(period)
    if not sign_match:
        msg = f"Invalid time format: {period}"
        raise ValueError(msg)

    sign = -1 if sign_match.group("sign") == "-" else 1
    unsigned = sign_match.group("unsigned")

    # Match time pattern
    if match := _TIME_PATTERN.match(unsigned):
        dct = match.groupdict()
        matches = {k: v for k, v in dct.items() if v is not None}
        try:
            secs = sum(_MULTIPLIERS[unit] * float(val) for unit, val in matches.items())
            return timedelta(seconds=sign * secs)
        except (ValueError, KeyError) as e:
            msg = f"Invalid time value in: {period}"
            raise ValueError(msg) from e

    msg = f"Unsupported time format: {period}"
    raise ValueError(msg)