23 lines
751 B
Python
23 lines
751 B
Python
"""Conversions between PostgreSQL timestamptz values, cursor integers and RFC 3339 strings."""
|
|
from __future__ import annotations
|
|
|
|
import datetime as dt
|
|
|
|
UTC = dt.timezone.utc
|
|
_EPOCH = dt.datetime(1970, 1, 1, tzinfo=UTC)
|
|
|
|
|
|
def to_us(value: dt.datetime) -> int:
|
|
"""Microseconds since the Unix epoch (exact: timestamptz has microsecond precision)."""
|
|
delta = value - _EPOCH
|
|
return (delta.days * 86_400 + delta.seconds) * 1_000_000 + delta.microseconds
|
|
|
|
|
|
def from_us(us: int) -> dt.datetime:
|
|
return _EPOCH + dt.timedelta(microseconds=us)
|
|
|
|
|
|
def rfc3339(value: dt.datetime) -> str:
|
|
"""RFC 3339 UTC with fixed microsecond precision, e.g. 2026-10-12T12:00:00.000001Z."""
|
|
return value.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|