TypeError: Cannot Compare Naive and Aware Datetimes

TypeError: can't compare offset-naive and offset-aware datetimes

Quick Answer

You are comparing a datetime with timezone info to one without. Make both timezone-aware or both naive. Use datetime.now(timezone.utc) for aware datetimes.

Why This Happens

Python datetimes can be naive (no timezone) or aware (with timezone). Comparing the two raises TypeError. Always use timezone-aware datetimes in production.

The Problem

from datetime import datetime, timezone
db_time = datetime(2024, 1, 15, tzinfo=timezone.utc)
now = datetime.now()
if now > db_time: pass

The Fix

from datetime import datetime, timezone
db_time = datetime(2024, 1, 15, tzinfo=timezone.utc)
now = datetime.now(timezone.utc)
if now > db_time: pass

Step-by-Step Fix

  1. 1

    Use timezone-aware datetimes

    Always use datetime.now(timezone.utc).

  2. 2

    Add timezone to naive datetimes

    Use naive_dt.replace(tzinfo=timezone.utc).

  3. 3

    Be consistent

    Use UTC everywhere, convert to local only for display.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free