Skip to content

gwmock.utils.datetime_parser

gwmock.utils.datetime_parser

Utilities for parsing human-readable time durations.

gwmock.utils.datetime_parser.parse_duration_to_seconds(duration)

Convert a human-friendly duration like "1 day" into seconds.

Parameters:

Name Type Description Default
duration str

A string such as "1 week", "2 days", "1.5 hours".

required

Returns:

Type Description
float

Number of seconds represented by the duration.

Raises:

Type Description
ValueError

If the string cannot be parsed or the unit is unsupported.

Source code in src/gwmock/utils/datetime_parser.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def parse_duration_to_seconds(duration: str) -> float:
    """Convert a human-friendly duration like "1 day" into seconds.

    Args:
        duration: A string such as "1 week", "2 days", "1.5 hours".

    Returns:
        Number of seconds represented by the duration.

    Raises:
        ValueError: If the string cannot be parsed or the unit is unsupported.
    """

    pattern = re.compile(r"^\s*(?P<value>\d+(?:\.\d+)?)\s*(?P<unit>\w+)s?\s*$", re.IGNORECASE)
    match = pattern.match(duration)
    if not match:
        raise ValueError("Duration must be of the form '<number> <unit>' (e.g. '1 week').")

    value = float(match.group("value"))
    unit = match.group("unit").lower().rstrip("s")

    seconds = SECOND_UNITS.get(unit)
    if seconds is None:
        raise ValueError(f"Unsupported duration unit '{unit}'. Supported units: {', '.join(SECOND_UNITS)}.")

    return value * seconds