149 lines
4.6 KiB
Python
149 lines
4.6 KiB
Python
"""Time helpers. Everything is stored in UTC; local time is only for display
|
|
and for deciding where "today" starts in the family's timezone."""
|
|
|
|
from dataclasses import dataclass
|
|
from datetime import date, datetime, time, timedelta, timezone
|
|
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError, available_timezones
|
|
|
|
|
|
def utcnow() -> datetime:
|
|
return datetime.now(timezone.utc)
|
|
|
|
|
|
def from_unix(ts: int | float) -> datetime:
|
|
return datetime.fromtimestamp(ts, timezone.utc)
|
|
|
|
|
|
def unix(dt: datetime) -> int:
|
|
return int(dt.timestamp())
|
|
|
|
|
|
def safe_zone(name: str | None) -> ZoneInfo:
|
|
try:
|
|
return ZoneInfo(name or "UTC")
|
|
except (ZoneInfoNotFoundError, ValueError):
|
|
return ZoneInfo("UTC")
|
|
|
|
|
|
def is_valid_zone(name: str) -> bool:
|
|
try:
|
|
ZoneInfo(name)
|
|
return True
|
|
except (ZoneInfoNotFoundError, ValueError):
|
|
return False
|
|
|
|
|
|
def zone_choices() -> list[str]:
|
|
return sorted(z for z in available_timezones() if "/" in z and not z.startswith(("Etc/", "SystemV/")))
|
|
|
|
|
|
def local_day_start(d: date, tz: ZoneInfo) -> datetime:
|
|
"""Local midnight of `d`, in UTC. DST-safe: zoneinfo picks the right offset."""
|
|
return datetime.combine(d, time.min, tzinfo=tz).astimezone(timezone.utc)
|
|
|
|
|
|
def local_day_bounds(d: date, tz: ZoneInfo) -> tuple[datetime, datetime]:
|
|
return local_day_start(d, tz), local_day_start(d + timedelta(days=1), tz)
|
|
|
|
|
|
def local_today(tz: ZoneInfo, now: datetime | None = None) -> date:
|
|
return (now or utcnow()).astimezone(tz).date()
|
|
|
|
|
|
def parse_local_input(value: str, tz: ZoneInfo) -> datetime | None:
|
|
"""Parse an <input type="datetime-local"> value ("2026-10-16T13:05") as local time."""
|
|
value = (value or "").strip()
|
|
if not value:
|
|
return None
|
|
naive = datetime.fromisoformat(value)
|
|
return naive.replace(tzinfo=tz).astimezone(timezone.utc)
|
|
|
|
|
|
def fmt_duration(seconds: float | None, *, short: bool = False) -> str:
|
|
"""3h 05m, 45m, 2d 4h. Rounded down to the minute."""
|
|
if seconds is None:
|
|
return ""
|
|
minutes = max(0, int(seconds // 60))
|
|
days, rem = divmod(minutes, 1440)
|
|
hours, mins = divmod(rem, 60)
|
|
if days:
|
|
return f"{days}d {hours}h"
|
|
if hours:
|
|
return f"{hours}h" if short and mins == 0 else f"{hours}h {mins:02d}m"
|
|
return f"{mins}m"
|
|
|
|
|
|
def baby_age(birth: date | None, today: date) -> str:
|
|
if birth is None or birth > today:
|
|
return ""
|
|
days = (today - birth).days
|
|
if days < 14:
|
|
return f"{days} day{'s' if days != 1 else ''} old"
|
|
if days < 7 * 13:
|
|
weeks, d = divmod(days, 7)
|
|
return f"{weeks} weeks" + (f" {d} day{'s' if d != 1 else ''}" if d else "")
|
|
months = (today.year - birth.year) * 12 + today.month - birth.month - (today.day < birth.day)
|
|
if months < 24:
|
|
return f"{months} months"
|
|
return f"{months // 12} years"
|
|
|
|
|
|
@dataclass
|
|
class Formatter:
|
|
"""Per-request display helpers, exposed to templates as `f`."""
|
|
|
|
tz: ZoneInfo
|
|
clock_24h: bool = False
|
|
|
|
def local(self, dt: datetime) -> datetime:
|
|
return dt.astimezone(self.tz)
|
|
|
|
def time(self, dt: datetime | None) -> str:
|
|
if dt is None:
|
|
return ""
|
|
lt = self.local(dt)
|
|
if self.clock_24h:
|
|
return lt.strftime("%H:%M")
|
|
return lt.strftime("%I:%M %p").lstrip("0").replace("AM", "am").replace("PM", "pm")
|
|
|
|
def hour_label(self, hour: int) -> str:
|
|
if self.clock_24h:
|
|
return f"{hour:02d}"
|
|
h = hour % 12 or 12
|
|
return f"{h}{'am' if hour % 24 < 12 else 'pm'}"
|
|
|
|
def day(self, d: date | datetime, today: date | None = None) -> str:
|
|
if isinstance(d, datetime):
|
|
d = self.local(d).date()
|
|
today = today or local_today(self.tz)
|
|
if d == today:
|
|
return "Today"
|
|
if d == today - timedelta(days=1):
|
|
return "Yesterday"
|
|
if (today - d).days < 7:
|
|
return d.strftime("%A")
|
|
return f"{d.strftime('%a %b')} {d.day}"
|
|
|
|
def day_short(self, d: date) -> str:
|
|
return f"{d.strftime('%a')[:2]} {d.day}"
|
|
|
|
def when(self, dt: datetime | None) -> str:
|
|
if dt is None:
|
|
return ""
|
|
return f"{self.day(dt)}, {self.time(dt)}"
|
|
|
|
def input_value(self, dt: datetime | None) -> str:
|
|
"""Value for <input type="datetime-local">."""
|
|
return self.local(dt).strftime("%Y-%m-%dT%H:%M") if dt else ""
|
|
|
|
def ago(self, dt: datetime | None, now: datetime | None = None) -> str:
|
|
if dt is None:
|
|
return "never"
|
|
secs = ((now or utcnow()) - dt).total_seconds()
|
|
if secs < 60:
|
|
return "just now"
|
|
return f"{fmt_duration(secs)} ago"
|
|
|
|
duration = staticmethod(fmt_duration)
|
|
unix = staticmethod(unix)
|