python.naive_datetime
Correctness
Medium
Detects datetime.now() without timezone or datetime.utcnow() usage, which creates naive datetime objects.
Why It Matters
Section titled “Why It Matters”Naive datetimes (those without timezone info) cause subtle bugs:
- Server location matters — Code behaves differently depending on where it runs
- Daylight saving bugs — Times shift unexpectedly twice a year
- Data corruption — Timestamps become ambiguous when stored and retrieved
- Distributed system chaos — Different services interpret the same timestamp differently
UTC awareness is essential for any system with multiple servers, users in different timezones, or data that persists.
Example
Section titled “Example”# ❌ Beforefrom datetime import datetime
now = datetime.now() # What timezone? Depends on server.# ✅ Afterfrom datetime import datetime, timezone
now = datetime.now(tz=timezone.utc)Always use UTC for storage and computation. Convert to local time only for display.
What Unfault Detects
Section titled “What Unfault Detects”datetime.now()withouttzparameterdatetime.utcnow()(deprecated, returns naive datetime)datetime.today()(naive datetime)
Auto-Fix
Section titled “Auto-Fix”Unfault adds tz=timezone.utc to datetime.now() calls and converts utcnow() to now(tz=timezone.utc).
Common Patterns
Section titled “Common Patterns”# ✅ Use timezone-aware datetimesfrom datetime import datetime, timezone
# Current time in UTCnow = datetime.now(tz=timezone.utc)
# Parse ISO format (Python 3.11+)dt = datetime.fromisoformat("2024-01-15T10:30:00+00:00")
# Store as ISO formattimestamp = now.isoformat()