def parse_timespan_attrib()

in azure/durable_functions/models/utils/json_utils.py [0:0]


def parse_timespan_attrib(from_str: str) -> datetime.timedelta:
    """Convert a string representing TimeSpan.ToString("c") in .NET to a python timedelta.

    Parameters
    ----------
    from_str: The string format of the TimeSpan to convert

    Returns
    -------
    timespan.timedelta
        The TimeSpan expressed as a Python datetime.timedelta

    """
    match = re.match(r"^(?P<negative>-)?(?:(?P<days>[0-9]*)\.)?"
                     r"(?P<hours>[0-9]{2}):(?P<minutes>[0-9]{2})"
                     r":(?P<seconds>[0-9]{2})(?:\.(?P<ticks>[0-9]{7}))?$",
                     from_str)
    if match:
        groups = match.groupdict()
        span = datetime.timedelta(
            days=int(groups['days'] or "0"),
            hours=int(groups['hours']),
            minutes=int(groups['minutes']),
            seconds=int(groups['seconds']),
            microseconds=int(groups['ticks'] or "0") // 10)

        if groups['negative'] == '-':
            span = -span
        return span
    else:
        raise Exception(f"Format of TimeSpan failed attempted conversion to timedelta: {from_str}")