timefmt.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """Small shared time-formatting helpers for CLI output."""
  2. from __future__ import annotations
  3. import logging
  4. import math
  5. import time as _time
  6. from datetime import datetime
  7. from typing import Any, Optional
  8. logger = logging.getLogger(__name__)
  9. # Epoch-seconds window a stored timestamp must fall in to be trusted: 1970 .. ~2103 (inside 32-bit
  10. # ``time_t`` so ``fromtimestamp`` accepts it on every platform). SQLite dynamic typing lets a TEXT
  11. # cell, ``inf``/``nan`` or a garbage double (``8.4e252`` salvaged from a damaged page) sit in a REAL
  12. # column; ``datetime.fromtimestamp`` then raises and one bad row killed the whole listing, export
  13. # or report (#102399, #102352, #99959).
  14. EPOCH_MIN = 0.0
  15. EPOCH_MAX = 4_200_000_000.0
  16. def coerce_epoch(value: Any, *, session_id: Optional[str] = None, field: str = "timestamp") -> Optional[float]:
  17. """A stored timestamp cell as float epoch seconds, or ``None`` when it cannot be trusted.
  18. Numbers, numeric strings and ``datetime`` are accepted; anything else, non-finite values and
  19. values outside ``EPOCH_MIN..EPOCH_MAX`` return ``None`` after a WARNING naming the session so
  20. the corrupt row can be found. ``None``/``""`` mean "unset" and stay silent. Every reader that
  21. renders a row timestamp goes through here (a bad row degrades to one ``?`` cell, never a dead
  22. command) and every writer uses it to refuse persisting a new bad row.
  23. """
  24. if value is None or value == "":
  25. return None
  26. try:
  27. ts = float(value.timestamp()) if isinstance(value, datetime) else float(value)
  28. except (TypeError, ValueError):
  29. ts = math.nan
  30. if not (EPOCH_MIN <= ts <= EPOCH_MAX): # also False for nan
  31. logger.warning("Ignoring corrupt %s %r%s", field, value, f" on session {session_id}" if session_id else "")
  32. return None
  33. return ts
  34. def relative_time(ts, *, session_id: Optional[str] = None) -> str:
  35. """Format a timestamp as relative time (e.g., '2h ago', 'yesterday'); ``?`` when unset or corrupt."""
  36. if not ts or (ts := coerce_epoch(ts, session_id=session_id, field="last_active")) is None:
  37. return "?"
  38. delta = _time.time() - ts
  39. if delta < 60:
  40. return "just now"
  41. if delta < 3600:
  42. return f"{int(delta / 60)}m ago"
  43. if delta < 86400:
  44. return f"{int(delta / 3600)}h ago"
  45. if delta < 172800:
  46. return "yesterday"
  47. if delta < 604800:
  48. return f"{int(delta / 86400)}d ago"
  49. return datetime.fromtimestamp(ts).strftime("%Y-%m-%d")