goduration

1from .parser import parse
2
3__version__ = "0.1.0"
4__all__ = ["parse"]
def parse(duration_str: str) -> datetime.timedelta:
 5def parse(duration_str: str) -> timedelta:
 6    if not isinstance(duration_str, str):
 7        raise TypeError(f"Expected string, got {type(duration_str)}")
 8
 9    s = duration_str.strip()
10    if not s:
11        raise ValueError("Empty duration string")
12
13    # Special case for "0"
14    if s == "0":
15        return timedelta(0)
16
17    is_negative = s.startswith("-")
18    is_positive = s.startswith("+")
19    if is_negative or is_positive:
20        s = s[1:]
21
22    total_minutes = 0
23    i = 0
24
25    while i < len(s):
26        # Parse number (including fractional)
27        num_start = i
28        while i < len(s) and (s[i].isdigit() or s[i] == "."):
29            i += 1
30
31        if i == num_start:
32            raise ValueError(f"Expected number at position {i}")
33
34        num = float(s[num_start:i])
35
36        # Parse unit (1-2 chars)
37        if i >= len(s):
38            raise ValueError(f"Missing unit after number {num}")
39
40        if i < len(s) - 1 and s[i : i + 2] in ["ns", "us", "µs", "μs", "ms"]:
41            unit = s[i : i + 2]
42            i += 2
43        else:
44            unit = s[i]
45            i += 1
46
47        # Convert to minutes
48        if unit == "ns":
49            total_minutes += num / (1000 * 1000 * 1000 * 60)
50        elif unit in ["us", "µs", "μs"]:
51            total_minutes += num / (1000 * 1000 * 60)
52        elif unit == "ms":
53            total_minutes += num / (1000 * 60)
54        elif unit == "s":
55            total_minutes += num / 60
56        elif unit == "m":
57            total_minutes += num
58        elif unit == "h":
59            total_minutes += num * 60
60        else:
61            raise ValueError(f"Invalid unit '{unit}', expected ns, us, ms, s, m, or h")
62
63    if is_negative:
64        total_minutes = -total_minutes
65
66    return timedelta(minutes=total_minutes)