|
| 1 | +# |
| 2 | +# SPDX-License-Identifier: MIT |
| 3 | +# |
| 4 | +# Visit https://aboutcode.org and https://github.com/aboutcode-org/univers for support and download. |
| 5 | + |
| 6 | +import re |
| 7 | +from datetime import datetime |
| 8 | +from datetime import timedelta |
| 9 | +from datetime import timezone |
| 10 | + |
| 11 | + |
| 12 | +class DatetimeVersion: |
| 13 | + """ |
| 14 | + datetime version. |
| 15 | +
|
| 16 | + The timestamp must be RFC3339-compliant, i.e., a subset of ISO8601, where the date AND time are always specified. Therefore, we cannot use an ISO-parser directly, but have to check for compliance with the RFC format via a regex. |
| 17 | + """ |
| 18 | + |
| 19 | + VERSION_PATTERN = re.compile( |
| 20 | + r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$" |
| 21 | + ) |
| 22 | + _TIME_TZ_RE = re.compile( |
| 23 | + r"^(?P<h>\d{2}):(?P<M>\d{2}):(?P<s>\d{2})(?:\.(?P<f>\d+))?(?P<tz>Z|[+-]\d{2}:\d{2})$" |
| 24 | + ) |
| 25 | + |
| 26 | + def __init__(self, version): |
| 27 | + version = str(version).strip() |
| 28 | + if not self.is_valid(version): |
| 29 | + raise InvalidVersionError(version) |
| 30 | + |
| 31 | + # save the original |
| 32 | + self.original = version |
| 33 | + |
| 34 | + # normalize Z to +00:00 to make tz parsing uniform |
| 35 | + if version.endswith("Z"): |
| 36 | + version = version[:-1] + "+00:00" |
| 37 | + |
| 38 | + # split into date and time+tz parts |
| 39 | + date_part, time_tz_part = version.split("T", 1) |
| 40 | + |
| 41 | + # parse the date-only portion first using fromisoformat |
| 42 | + # (datetime.fromisoformat accepts date-only strings) |
| 43 | + try: |
| 44 | + dt = datetime.fromisoformat(date_part) |
| 45 | + except ValueError: |
| 46 | + raise InvalidVersionError(version) |
| 47 | + |
| 48 | + # parse time and timezone with regex |
| 49 | + m = self._TIME_TZ_RE.fullmatch(time_tz_part) |
| 50 | + if not m: |
| 51 | + raise InvalidVersionError(version) |
| 52 | + |
| 53 | + hour = int(m.group("h")) |
| 54 | + minute = int(m.group("M")) |
| 55 | + second = int(m.group("s")) |
| 56 | + frac = m.group("f") or "" |
| 57 | + # ensure microseconds length is exactly 6 (truncate or pad), because datetime requires that |
| 58 | + if frac: |
| 59 | + micro = int((frac[:6]).ljust(6, "0")) |
| 60 | + else: |
| 61 | + micro = 0 |
| 62 | + |
| 63 | + leap_second = second == 60 |
| 64 | + if leap_second: |
| 65 | + # we can't handle second=60, so we use 59 and add one second later |
| 66 | + second = 59 |
| 67 | + |
| 68 | + tz_text = m.group("tz") |
| 69 | + sign = 1 if tz_text[0] == "+" else -1 |
| 70 | + tzh = int(tz_text[1:3]) |
| 71 | + tzm = int(tz_text[4:6]) |
| 72 | + offset = sign * (tzh * 3600 + tzm * 60) |
| 73 | + tzinfo = timezone(timedelta(seconds=offset)) |
| 74 | + |
| 75 | + # construct aware datetime for the exact instant |
| 76 | + dt = datetime( |
| 77 | + year=dt.year, |
| 78 | + month=dt.month, |
| 79 | + day=dt.day, |
| 80 | + hour=hour, |
| 81 | + minute=minute, |
| 82 | + second=second, |
| 83 | + microsecond=micro, |
| 84 | + tzinfo=tzinfo, |
| 85 | + ) |
| 86 | + |
| 87 | + if leap_second: |
| 88 | + dt = dt + timedelta(seconds=1) |
| 89 | + |
| 90 | + # canonicalize to UTC for comparisons/hashing |
| 91 | + self.parsed_stamp = dt.astimezone(timezone.utc) |
| 92 | + |
| 93 | + def __eq__(self, other): |
| 94 | + return self.parsed_stamp == other.parsed_stamp |
| 95 | + |
| 96 | + def __lt__(self, other): |
| 97 | + return self.parsed_stamp < other.parsed_stamp |
| 98 | + |
| 99 | + def __le__(self, other): |
| 100 | + return self.parsed_stamp <= other.parsed_stamp |
| 101 | + |
| 102 | + def __gt__(self, other): |
| 103 | + return self.parsed_stamp > other.parsed_stamp |
| 104 | + |
| 105 | + def __ge__(self, other): |
| 106 | + return self.parsed_stamp >= other.parsed_stamp |
| 107 | + |
| 108 | + @classmethod |
| 109 | + def is_valid(cls, string): |
| 110 | + return bool(cls.VERSION_PATTERN.fullmatch(string)) |
| 111 | + |
| 112 | + |
| 113 | +class InvalidVersionError(ValueError): |
| 114 | + pass |
0 commit comments