from datetime import datetime, timezone def isoformat_utc(dt: datetime | None) -> str | None: """Serialize a datetime for API responses, stamping it UTC first. Every DateTime column is written via app.db.models.utcnow() but SQLite/aiosqlite round-trips it as a naive datetime, so a bare .isoformat() drops the "Z"/offset and JavaScript's `new Date()` on the frontend parses the result as local time instead of UTC (B-35). All stored values are UTC in practice, so a naive value can be safely stamped rather than converted. """ if dt is None: return None if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) return dt.isoformat()