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

Feb 24, 2021

It meanse one of the datetime instance contains timezone info, while the others doens't.

import datetimed1 = datetime.datetime.now(datetime.timezone.utc) # datetime.datetime(2021, 2, 24, 4, 30, 6, 598645, tzinfo=datetime.timezone.utc)d2 = datetime.datetime.utcnow()                   # datetime.datetime(2021, 2, 24, 4, 30, 14, 29200)diff = d2 - d1  # TypeError: can't subtract offset-naive and offset-aware datetim

You can either remove timzeone info

diff = d2 - d1.replace(tzinfo=None) 

Or add timezone info

diff = d2.replace(tzinfo=datetime.timezone.utc) - d1

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.