douyinWEB/backend/app/timeutil.py
2026-08-10 20:11:23 -05:00

60 lines
1.8 KiB
Python

"""Beijing time (Asia/Shanghai) helpers — all calendar dates / local hours use this."""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from typing import Optional
from zoneinfo import ZoneInfo
BJ = ZoneInfo("Asia/Shanghai")
UTC = timezone.utc
def beijing_now() -> datetime:
return datetime.now(BJ)
def beijing_from_ts(ts: float | int | None) -> datetime:
"""Unix timestamp → aware datetime in Beijing."""
return datetime.fromtimestamp(float(ts or 0), BJ)
def beijing_hour(ts: float | int | None = None) -> int:
if ts is None:
return beijing_now().hour
return beijing_from_ts(ts).hour
def push_date_from_ts(ts: float | int | None) -> str:
return beijing_from_ts(ts).strftime("%Y-%m-%d")
def format_beijing(ts: float | int | None, fmt: str = "%Y-%m-%d %H:%M:%S") -> str:
if not ts:
return ""
return beijing_from_ts(ts).strftime(fmt)
def stamp_beijing(fmt: str = "%Y%m%d_%H%M%S") -> str:
return beijing_now().strftime(fmt)
def next_hour_boundary_ts(ts: float) -> float:
"""Next Beijing clock-hour boundary after ts (exclusive of exact hour start → +1h)."""
dt = beijing_from_ts(ts).replace(minute=0, second=0, microsecond=0)
return (dt + timedelta(hours=1)).timestamp()
def beijing_today_at(hour: int, minute: int = 0) -> datetime:
now = beijing_now()
return now.replace(hour=int(hour) % 24, minute=int(minute) % 60, second=0, microsecond=0)
def beijing_day_bounds(push_date: str = "") -> tuple[float, float]:
"""Beijing calendar day [start, end) as Unix timestamps for push_date (default today)."""
day = push_date or push_date_from_ts(time.time())
y, m, d = [int(x) for x in day.split("-")]
start = datetime(y, m, d, 0, 0, 0, tzinfo=BJ)
end = start + timedelta(days=1)
return start.timestamp(), end.timestamp()