Files
mtusi2026lab3/app/timeutil.py
T
2026-11-02 20:05:33 +03:00

24 lines
797 B
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Преобразования времени: RFC 3339 UTC и микросекунды."""
from datetime import datetime, timedelta, timezone
EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
def format_ts(moment: datetime) -> str:
"""datetime -> строка RFC 3339 в UTC с суффиксом Z."""
return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def to_micros(moment: datetime) -> int:
"""datetime -> микросекунды от эпохи."""
return (moment - EPOCH) // timedelta(microseconds=1)
MAX_TIMESTAMP_MICROS = to_micros(datetime.max.replace(tzinfo=timezone.utc))
def from_micros(micros: int) -> datetime:
"""Микросекунды от эпохи -> datetime в UTC."""
return EPOCH + timedelta(microseconds=micros)