Skip to content

python.naive_datetime

Correctness Medium

Detects datetime.now() without timezone or datetime.utcnow() usage, which creates naive datetime objects.

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.

# ❌ Before
from datetime import datetime
now = datetime.now() # What timezone? Depends on server.
# ✅ After
from datetime import datetime, timezone
now = datetime.now(tz=timezone.utc)

Always use UTC for storage and computation. Convert to local time only for display.

  • datetime.now() without tz parameter
  • datetime.utcnow() (deprecated, returns naive datetime)
  • datetime.today() (naive datetime)

Unfault adds tz=timezone.utc to datetime.now() calls and converts utcnow() to now(tz=timezone.utc).

# ✅ Use timezone-aware datetimes
from datetime import datetime, timezone
# Current time in UTC
now = datetime.now(tz=timezone.utc)
# Parse ISO format (Python 3.11+)
dt = datetime.fromisoformat("2024-01-15T10:30:00+00:00")
# Store as ISO format
timestamp = now.isoformat()