TypeError when you subtract or compare two Python datetimes
TypeError: can't subtract offset-naive and offset-aware datetimesShort 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.
Fix it fast
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())2Match what you see, then jump to its fix
- 1
One 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
The 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
The whole code base stores local wall-clock time and the one aware value is an outlierYou really want naive values on both sidesFix
- 1
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) # UTC2Fix
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 aware3Verify
The subtraction returns a timedelta.
print(elapsed)Confirmed by docs.python.org
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
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
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:
- stegnor.comMy company site: 804 pages from a Python and Jinja generator, with 15 free browser tools.
- MenuloA restaurant discovery platform in Germany, kept current by a Python ingestion pipeline.
- ShopGoAn e-commerce aggregator with a Python scraping engine behind its catalog, past 10K Google Play downloads.
Related fixes
Databases
Installing the Airflow MySQL provider fails on pkg-config or mysqlclient
Building the mysqlclient wheel fails during the install
The Airflow MySQL provider depends on mysqlclient, which pip compiles against the MySQL C client library.
2 causes, each with a fixDatabases
asyncpg InterfaceError: another operation is in progress with SQLAlchemy
InterfaceError raised from a FastAPI endpoint that runs several queries at once
A single database connection can run one operation at a time.
4 causes, each with a fixDatabases
Django cannot load MySQLdb and asks whether mysqlclient is installed
Error loading MySQLdb module: Did you install mysqlclient or MySQL-python?
Django's MySQL backend imports MySQLdb, which is provided by the mysqlclient package.
3 causes, each with a fixDatabases
python manage.py migrate finishes but the tables for my app are missing
relation "myapp_book" does not exist
migrate only applies migration files that exist.
3 causes, each with a fixDatabases
Django save fails on PostgreSQL: null value in a column violates a not-null constraint
django.db.utils.IntegrityError: null value in column "price" of relation "shop_product" violates not-null constraint
A model field is NOT NULL in the database unless it has null=True.
3 causes, each with a fixDatabases
Django migration on PostgreSQL stops with 'pending trigger events'
django.db.utils.OperationalError: cannot ALTER TABLE "mytable" because it has pending trigger events
PostgreSQL runs a Django migration in one transaction.
2 causes, each with a fix