Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Databases and Redis

TypeError when you subtract or compare two Python datetimes

ErrorTypeError: can't subtract offset-naive and offset-aware datetimes

Short answer

Python refuses to subtract or order a datetime that has a time zone against one that has none. Find the naive value (utcoffset() returns None), then either make it aware with the correct zone or make both naive on purpose. Prefer aware values in UTC everywhere inside the app.

  • Applies to Python 3.12, Python 3.13
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Print which of the two values has no time zone. An aware datetime returns an offset here; a naive one returns None.

    print(a.utcoffset())
    print(b.utcoffset())
  2. 2Match what you see, then jump to its fix

    1. 1One utcoffset() prints None and the other prints something like 0:00:00One value comes from datetime.now() or utcnow(), the other from a database or API with a zoneFix
    2. 2The naive value came from user input, a CSV or a database column without time zone, and it is local time, not UTCA naive value is really in some zone and you need to attach itFix
    3. 3The whole code base stores local wall-clock time and the one aware value is an outlierYou really want naive values on both sidesFix

What does the error look like?

  • TypeError: can't subtract offset-naive and offset-aware datetimes

Cause 1 of 3

One value comes from datetime.now() or utcnow(), the other from a database or API with a zone

1Check

datetime.now() with no argument and datetime.utcnow() both return naive objects. A timestamp parsed from a string that ends in Z or +00:00 is aware. Subtracting the two raises the TypeError.

from datetime import datetime, timezone
print(datetime.now().tzinfo)               # None
print(datetime.now(timezone.utc).tzinfo)   # UTC

2Fix

Create the current time as an aware UTC value. The Python docs name datetime.now(timezone.utc) as the recommended way, and utcnow() is deprecated since 3.12.

from datetime import datetime, timezone
now = datetime.now(timezone.utc)
elapsed = now - created_at   # created_at must also be aware

3Verify

The subtraction returns a timedelta.

print(elapsed)

Confirmed by docs.python.org

Did this fix it?

Cause 2 of 3

A naive value is really in some zone and you need to attach it

1Check

Decide what zone the naive value is in before you touch it. Attaching the wrong zone silently shifts every result.

print(value, value.tzinfo)

2Fix

If the naive value is already in UTC, attach it without changing the clock fields with replace(tzinfo=...). If it is in another zone, attach that zone first, then convert with astimezone().

from datetime import timezone
from zoneinfo import ZoneInfo
# already UTC:
aware = value.replace(tzinfo=timezone.utc)
# local time in a named zone:
aware = value.replace(tzinfo=ZoneInfo("Europe/Berlin")).astimezone(timezone.utc)

3Verify

Both operands now report an offset and the comparison runs.

print(aware.utcoffset(), aware > other)

Confirmed by docs.python.org

Did this fix it?

Cause 3 of 3

You really want naive values on both sides

1Check

Check where the aware value enters (a parsed ISO string, a library that returns UTC). Mixing is the bug, not the zone.

print(other.tzinfo)

2Fix

Drop the zone from the aware value with replace(tzinfo=None). This changes the type only and does no conversion, so convert to the zone you want first with astimezone().

from datetime import timezone
naive = other.astimezone(timezone.utc).replace(tzinfo=None)

3Verify

Both values are naive and subtract without an error.

print(naive.tzinfo, a - naive)

Confirmed by docs.python.org

Did this fix it?

How do I stop it coming back?

  • Store and compute in aware UTC, and convert to a local zone only when you show a value to a person.
  • Replace utcnow() and utcfromtimestamp() with calls that pass timezone.utc.
  • Use timezone-aware columns for timestamps in your database, so values come back with an offset.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.