| 1 |
|
| 2 |
|
| 3 |
import datetime as dt |
| 4 |
from email.utils import parsedate_to_datetime |
| 5 |
from typing import Any |
| 6 |
|
| 7 |
import pydantic |
| 8 |
|
| 9 |
IS_PYDANTIC_V2 = pydantic.VERSION.startswith("2.") |
| 10 |
|
| 11 |
|
| 12 |
def parse_rfc2822_datetime(v: Any) -> dt.datetime: |
| 13 |
""" |
| 14 |
Parse an RFC 2822 datetime string (e.g., "Wed, 02 Oct 2002 13:00:00 GMT") |
| 15 |
into a datetime object. If the value is already a datetime, return it as-is. |
| 16 |
Falls back to ISO 8601 parsing if RFC 2822 parsing fails. |
| 17 |
""" |
| 18 |
if isinstance(v, dt.datetime): |
| 19 |
return v |
| 20 |
if isinstance(v, str): |
| 21 |
try: |
| 22 |
return parsedate_to_datetime(v) |
| 23 |
except Exception: |
| 24 |
pass |
| 25 |
|
| 26 |
return dt.datetime.fromisoformat(v.replace("Z", "+00:00")) |
| 27 |
raise ValueError(f"Expected str or datetime, got {type(v)}") |
| 28 |
|
| 29 |
|
| 30 |
class Rfc2822DateTime(dt.datetime): |
| 31 |
"""A datetime subclass that parses RFC 2822 date strings. |
| 32 |
|
| 33 |
On Pydantic V1, uses __get_validators__ for pre-validation. |
| 34 |
On Pydantic V2, uses __get_pydantic_core_schema__ for BeforeValidator-style parsing. |
| 35 |
""" |
| 36 |
|
| 37 |
@classmethod |
| 38 |
def __get_validators__(cls): |
| 39 |
yield parse_rfc2822_datetime |
| 40 |
|
| 41 |
@classmethod |
| 42 |
def __get_pydantic_core_schema__(cls, _source_type: Any, _handler: Any) -> Any: |
| 43 |
from pydantic_core import core_schema |
| 44 |
|
| 45 |
return core_schema.no_info_before_validator_function(parse_rfc2822_datetime, core_schema.datetime_schema()) |
| 46 |
|
| 47 |
|
| 48 |
def serialize_datetime(v: dt.datetime) -> str: |
| 49 |
""" |
| 50 |
Serialize a datetime including timezone info. |
| 51 |
|
| 52 |
Uses the timezone info provided if present, otherwise uses the current runtime's timezone info. |
| 53 |
|
| 54 |
UTC datetimes end in "Z" while all other timezones are represented as offset from UTC, e.g. +05:00. |
| 55 |
""" |
| 56 |
|
| 57 |
def _serialize_zoned_datetime(v: dt.datetime) -> str: |
| 58 |
if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None): |
| 59 |
|
| 60 |
return v.isoformat().replace("+00:00", "Z") |
| 61 |
else: |
| 62 |
|
| 63 |
return v.isoformat() |
| 64 |
|
| 65 |
if v.tzinfo is not None: |
| 66 |
return _serialize_zoned_datetime(v) |
| 67 |
else: |
| 68 |
local_tz = dt.datetime.now().astimezone().tzinfo |
| 69 |
localized_dt = v.replace(tzinfo=local_tz) |
| 70 |
return _serialize_zoned_datetime(localized_dt) |