| 1 |
from datetime import datetime, timezone, tzinfo |
| 2 |
|
| 3 |
|
| 4 |
def datetime_exists(dt): |
| 5 |
"""Check if a datetime exists. Taken from: https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html""" |
| 6 |
# There are no non-existent times in UTC, and comparisons between |
| 7 |
# aware time zones always compare absolute times; if a datetime is |
| 8 |
# not equal to the same datetime represented in UTC, it is imaginary. |
| 9 |
return dt.astimezone(timezone.utc) == dt |
| 10 |
|
| 11 |
|
| 12 |
def datetime_ambiguous(dt: datetime): |
| 13 |
"""Check whether a datetime is ambiguous. Taken from: https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html""" |
| 14 |
# If a datetime exists and its UTC offset changes in response to |
| 15 |
# changing `fold`, it is ambiguous in the zone specified. |
| 16 |
return datetime_exists(dt) and ( |
| 17 |
dt.replace(fold=not dt.fold).utcoffset() != dt.utcoffset() |
| 18 |
) |
| 19 |
|
| 20 |
|
| 21 |
def valid_datetime(dt): |
| 22 |
"""Returns True if the datetime is not ambiguous or imaginary, False otherwise.""" |
| 23 |
if isinstance(dt.tzinfo, tzinfo) and not datetime_ambiguous(dt): |
| 24 |
return True |
| 25 |
return False |