forked from linkong/planet
26 lines
716 B
Python
26 lines
716 B
Python
"""Time helpers for API serialization."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import UTC, datetime
|
|
|
|
|
|
def ensure_utc(value: datetime | str | None) -> datetime | None:
|
|
if value is None:
|
|
return None
|
|
if isinstance(value, str):
|
|
stripped = value.strip()
|
|
if not stripped:
|
|
return None
|
|
value = datetime.fromisoformat(stripped.replace("Z", "+00:00"))
|
|
if value.tzinfo is None:
|
|
return value.replace(tzinfo=UTC)
|
|
return value.astimezone(UTC)
|
|
|
|
|
|
def to_iso8601_utc(value: datetime | str | None) -> str | None:
|
|
normalized = ensure_utc(value)
|
|
if normalized is None:
|
|
return None
|
|
return normalized.isoformat().replace("+00:00", "Z")
|