|
| 1 | +from sys import version_info as sys_version_info |
| 2 | +import re |
| 3 | +from datetime import datetime, time, timedelta |
| 4 | + |
| 5 | +_ISO8601_DURATION_PATTERN = re.compile( |
| 6 | + "^P" # Duration P indicator |
| 7 | + # Weeks |
| 8 | + "(?P<w>" |
| 9 | + r" (?P<weeks>\d+(?:[.,]\d+)?W)" |
| 10 | + ")?" |
| 11 | + # Years, Months, Days |
| 12 | + "(?P<ymd>" |
| 13 | + r" (?P<years>\d+(?:[.,]\d+)?Y)?" |
| 14 | + r" (?P<months>\d+(?:[.,]\d+)?M)?" |
| 15 | + r" (?P<days>\d+(?:[.,]\d+)?D)?" |
| 16 | + ")?" |
| 17 | + # Time |
| 18 | + "(?P<hms>" |
| 19 | + " (?P<timesep>T)" # Separator (T) |
| 20 | + r" (?P<hours>\d+(?:[.,]\d+)?H)?" |
| 21 | + r" (?P<minutes>\d+(?:[.,]\d+)?M)?" |
| 22 | + r" (?P<seconds>\d+(?:[.,]\d+)?S)?" |
| 23 | + ")?" |
| 24 | + "$", |
| 25 | + re.VERBOSE, |
| 26 | +) |
| 27 | + |
| 28 | + |
| 29 | +def parse_timedelta_from_iso_format(text: str) -> timedelta: |
| 30 | + """Parses a ISO8601 duration string into a timedelta object.""" |
| 31 | + |
| 32 | + m = _ISO8601_DURATION_PATTERN.match(text) |
| 33 | + if not m: |
| 34 | + raise ValueError(f"Invalid ISO8601 duration string: {text}") |
| 35 | + |
| 36 | + weeks = float(m.group("weeks").replace(",", ".").replace("W", "")) if m.group("weeks") else 0 |
| 37 | + years = float(m.group("years").replace(",", ".").replace("Y", "")) if m.group("years") else 0 |
| 38 | + months = float(m.group("months").replace(",", ".").replace("M", "")) if m.group("months") else 0 |
| 39 | + days = float(m.group("days").replace(",", ".").replace("D", "")) if m.group("days") else 0 |
| 40 | + hours = float(m.group("hours").replace(",", ".").replace("H", "")) if m.group("hours") else 0 |
| 41 | + minutes = float(m.group("minutes").replace(",", ".").replace("M", "") |
| 42 | + ) if m.group("minutes") else 0 |
| 43 | + seconds = float(m.group("seconds").replace(",", ".").replace("S", "") |
| 44 | + ) if m.group("seconds") else 0 |
| 45 | + _have_date = years or months or days |
| 46 | + _have_time = hours or minutes or seconds |
| 47 | + if weeks and (_have_date or _have_time): |
| 48 | + raise ValueError("Combining weeks with other date/time parts is not supported") |
| 49 | + |
| 50 | + _total_days = (years * 365) + (months * 30) + days |
| 51 | + return timedelta( |
| 52 | + days=_total_days, |
| 53 | + hours=hours, |
| 54 | + minutes=minutes, |
| 55 | + seconds=seconds, |
| 56 | + weeks=weeks, |
| 57 | + ) |
| 58 | + |
| 59 | + |
| 60 | +_TIMEDELTA_PATTERN = re.compile(r"^(?P<hours>\d+):(?P<minutes>\d+)(?::(?P<seconds>\d+))?$") |
| 61 | + |
| 62 | + |
| 63 | +def parse_timedelta_string(text: str) -> timedelta: |
| 64 | + """Checks if a given string is a valid ISO8601 duration string. Or hh:mm:ss format.""" |
| 65 | + try: |
| 66 | + return parse_timedelta_from_iso_format(text) |
| 67 | + except ValueError as exc: |
| 68 | + # The previous library also supported hh:mm:ss format |
| 69 | + m = _TIMEDELTA_PATTERN.match(text) |
| 70 | + if not m: |
| 71 | + raise ValueError(f"Invalid timedelta string: {text}") from exc |
| 72 | + |
| 73 | + hours = int(m.group("hours")) |
| 74 | + minutes = int(m.group("minutes")) |
| 75 | + seconds = int(m.group("seconds") or 0) |
| 76 | + return timedelta(hours=hours, minutes=minutes, seconds=seconds) |
| 77 | + |
| 78 | + |
| 79 | +_TIME_REPLACEMENT_PATTERN = re.compile(r'(\d)([.,])(\d+)') |
| 80 | + |
| 81 | + |
| 82 | +def datetime_from_iso_format_compat(text: str) -> datetime: |
| 83 | + """Parses a ISO8601 formatted string into a datetime object.""" |
| 84 | + try: |
| 85 | + # Try regular first (faster for most cases) |
| 86 | + return datetime.fromisoformat(text) |
| 87 | + except ValueError as exc: |
| 88 | + # Python 3.10 and below only support fractions of seconds in either 3 or 6 digits |
| 89 | + # Python 3.11+ supports any number of digits |
| 90 | + |
| 91 | + if sys_version_info[:3] < (3, 11): |
| 92 | + # The following code is a workaround for Python 3.10 and below |
| 93 | + fixed_time = re.sub( |
| 94 | + _TIME_REPLACEMENT_PATTERN, |
| 95 | + lambda x: x.group(1) + "." + x.group(3).ljust(6, '0')[:6], text |
| 96 | + ).replace("Z", "+00:00") |
| 97 | + return datetime.fromisoformat(fixed_time) |
| 98 | + |
| 99 | + raise exc |
| 100 | + |
| 101 | + |
| 102 | +def time_from_iso_format_compat(text: str) -> time: |
| 103 | + """Parses a ISO8601 formatted string into a time object.""" |
| 104 | + try: |
| 105 | + # Try regular first (faster for most cases) |
| 106 | + return time.fromisoformat(text) |
| 107 | + except ValueError as exc: |
| 108 | + # Python 3.10 and below only support fractions of seconds in either 3 or 6 digits |
| 109 | + # Python 3.11+ supports any number of digits |
| 110 | + |
| 111 | + if sys_version_info[:3] < (3, 11): |
| 112 | + # The following code is a workaround for Python 3.10 and below |
| 113 | + fixed_time = re.sub( |
| 114 | + _TIME_REPLACEMENT_PATTERN, |
| 115 | + lambda x: x.group(1) + "." + x.group(3).ljust(6, '0')[:6], text |
| 116 | + ).replace("Z", "+00:00") |
| 117 | + return time.fromisoformat(fixed_time) |
| 118 | + |
| 119 | + raise exc |
0 commit comments