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
Telling naive and aware datetimes apart
Fix 1: make both aware (recommended)
replace(tzinfo=...) assumes the naive value was already in that timezone. It attaches the zone without converting the time.
Fix 2: make both naive
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)
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+)
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:
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.
Habits that prevent the error
- Do not treat
datetime.utcnow()as aware. It returns a naive datetime that happens to be in UTC, withtzinfo=None, so subtracting it from an aware value still raisesTypeError. It is deprecated in Python 3.12. Usedatetime.now(timezone.utc). - Do duration math in UTC. Convert both values with
astimezone(timezone.utc)before subtracting. When two aware datetimes share the sametzinfoobject, 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.
Related reading
- Cartesian product of x and y array points into single array of 2D points
- case-insensitive list sorting, without lowercasing the result?
- Case insensitive 'in
- Case insensitive regular expression without re.compile?
- Can't use a MySQL connection for entity framework 6
- CardView background color always white
- Cassandra 3.1 python driver 'no viable alternative at input describe
- Catch and print full Python exception traceback without halting/exiting the program
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo 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 courseData 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.