Python
datetime
timezone
programming error
date manipulation

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

Codemia Knowledge Hub ·

Python raises this when one datetime is naive (tzinfo=None) and the other is aware (it carries timezone data). Make both aware or both naive before subtracting. Usually that means creating aware values with datetime.now(timezone.utc) and attaching a timezone to the naive one with replace(tzinfo=...). Stripping the timezone with dt.replace(tzinfo=None) also works, but throws information away.

Reproducing the error

python
1from datetime import datetime, timezone
2
3naive = datetime(2024, 6, 15, 12, 0, 0)         # No timezone
4aware = datetime(2024, 6, 15, 12, 0, 0, tzinfo=timezone.utc)  # UTC
5
6diff = aware - naive
7# TypeError: can't subtract offset-naive and offset-aware datetimes

Telling naive and aware datetimes apart

python
1from datetime import datetime, timezone
2
3# Naive — no timezone information
4naive = datetime.now()
5print(naive.tzinfo)  # None
6
7# Aware — has timezone information
8aware = datetime.now(timezone.utc)
9print(aware.tzinfo)  # UTC
10
11# Check if a datetime is naive or aware
12def is_aware(dt):
13    return dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None
14
15print(is_aware(naive))  # False
16print(is_aware(aware))  # True
python
1from datetime import datetime, timezone
2
3# Make naive datetime aware by adding UTC timezone
4naive = datetime(2024, 6, 15, 12, 0, 0)
5aware = datetime.now(timezone.utc)
6
7# Option A: replace tzinfo (assumes the naive time is UTC)
8naive_as_utc = naive.replace(tzinfo=timezone.utc)
9diff = aware - naive_as_utc
10print(diff)  # timedelta result
11
12# Option B: use zoneinfo (Python 3.9+)
13from zoneinfo import ZoneInfo
14
15naive_as_eastern = naive.replace(tzinfo=ZoneInfo("America/New_York"))
16diff = aware - naive_as_eastern
17print(diff)

replace(tzinfo=...) assumes the naive value was already in that timezone. It attaches the zone without converting the time.

Fix 2: make both naive

python
1from datetime import datetime, timezone
2
3aware = datetime.now(timezone.utc)
4naive = datetime(2024, 6, 15, 12, 0, 0)
5
6# Strip timezone from the aware datetime
7aware_as_naive = aware.replace(tzinfo=None)
8diff = aware_as_naive - naive
9print(diff)  # Works — both are naive now

This discards timezone information, so only use it when you know both values represent the same timezone. If they were in different zones, the result is silently wrong.

Fix 3: localize with pytz (before Python 3.9)

python
1import pytz
2from datetime import datetime
3
4# Localize a naive datetime to a timezone
5eastern = pytz.timezone("America/New_York")
6naive = datetime(2024, 6, 15, 12, 0, 0)
7
8# CORRECT way to make aware with pytz
9aware_eastern = eastern.localize(naive)
10
11# Now subtract from another aware datetime
12utc_now = datetime.now(pytz.utc)
13diff = utc_now - aware_eastern
14print(diff)

With pytz, use tz.localize(naive_dt) rather than replace(tzinfo=tz). replace attaches the zone blindly, and for pytz zones with historical offset changes that can produce incorrect times. Keep replace() for fixed-offset zones like timezone.utc.

Fix 4: create aware values with zoneinfo (Python 3.9+)

python
1from datetime import datetime, timezone
2from zoneinfo import ZoneInfo
3
4# Create aware datetimes directly
5utc_time = datetime(2024, 6, 15, 16, 0, 0, tzinfo=timezone.utc)
6tokyo_time = datetime(2024, 6, 16, 1, 0, 0, tzinfo=ZoneInfo("Asia/Tokyo"))
7
8# Subtraction works — both are aware
9diff = tokyo_time - utc_time
10print(diff)  # 0:00:00 (same instant in time)

Pick one library, pytz or zoneinfo, and use it consistently. pytz.timezone("US/Eastern") and ZoneInfo("US/Eastern") produce different tzinfo objects, and mixing them in comparisons or subtraction can give unexpected results.

Datetimes from a database

Databases often return naive datetimes even when the stored value is UTC:

python
1from datetime import datetime, timezone
2
3# Simulating a database result (naive, but actually UTC)
4db_created_at = datetime(2024, 6, 15, 12, 0, 0)  # From database
5
6# Application code uses aware datetimes
7now = datetime.now(timezone.utc)
8
9# Option 1: Make the DB datetime aware
10created_utc = db_created_at.replace(tzinfo=timezone.utc)
11age = now - created_utc
12
13# Option 2: Configure your DB driver to return aware datetimes
14# SQLAlchemy:
15#   Column(DateTime(timezone=True))
16# Django:
17#   USE_TZ = True in settings.py
18# psycopg2:
19#   Automatically returns aware datetimes for timestamptz columns

pandas Timestamps

pandas Timestamps and datetime columns can also be naive or aware. Localize naive values with tz_localize and convert between zones with tz_convert.

python
1import pandas as pd
2from datetime import datetime, timezone
3
4# pandas Timestamps can be naive or aware
5naive_ts = pd.Timestamp("2024-06-15 12:00:00")
6aware_ts = pd.Timestamp("2024-06-15 12:00:00", tz="UTC")
7
8# Localize naive to aware
9aware_ts = naive_ts.tz_localize("UTC")
10
11# Convert between timezones
12eastern_ts = aware_ts.tz_convert("America/New_York")
13
14# For entire Series/DataFrame columns
15df = pd.DataFrame({"date": pd.to_datetime(["2024-01-01", "2024-06-15"])})
16df["date_utc"] = df["date"].dt.tz_localize("UTC")
17df["date_eastern"] = df["date_utc"].dt.tz_convert("America/New_York")

Habits that prevent the error

python
1from datetime import datetime, timezone
2
3# ALWAYS create aware datetimes
4now = datetime.now(timezone.utc)          # Preferred over datetime.utcnow()
5# datetime.utcnow() returns a NAIVE datetime in UTC — confusing and deprecated in 3.12
6
7# When parsing strings, always specify timezone
8from datetime import datetime
9from zoneinfo import ZoneInfo
10
11parsed = datetime.fromisoformat("2024-06-15T12:00:00+00:00")  # Aware
12parsed_naive = datetime.fromisoformat("2024-06-15T12:00:00")   # Naive — avoid
13
14# Store as UTC, display in local timezone
15utc_time = datetime.now(timezone.utc)
16local_time = utc_time.astimezone(ZoneInfo("America/Los_Angeles"))
17print(local_time.strftime("%Y-%m-%d %I:%M %p %Z"))
  • Do not treat datetime.utcnow() as aware. It returns a naive datetime that happens to be in UTC, with tzinfo=None, so subtracting it from an aware value still raises TypeError. It is deprecated in Python 3.12. Use datetime.now(timezone.utc).
  • Do duration math in UTC. Convert both values with astimezone(timezone.utc) before subtracting. When two aware datetimes share the same tzinfo object, Python ignores the offsets and subtracts the wall-clock times, and naive values behave the same way, so either can be off by an hour across a DST transition.
  • Store UTC, display local. Keep timestamps in UTC in the database and convert to a local timezone only for display.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms