Lessons · Python · a time that knows its timezone
A time that knows where it is
A naive datetime carries no timezone; an aware one does. Python refuses to subtract one from the other, because the answer would be a guess.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
A server in one zone, a user in another, an API returning UTC: mixing them is how appointments land an hour off and 'is it expired' checks fail at midnight.
How to think about it
Make everything aware and keep it in UTC inside the program: datetime.now(timezone.utc). Convert to a local zone only at the edge, when a person will read it.
Worked example
from datetime import datetime, timezoneThe two names you need.
naive = datetime(2026, 1, 1)No zone.
aware = datetime(2026, 1, 1, tzinfo=timezone.utc)Knows it is UTC.
print(naive.tzinfo, aware.tzinfo)None UTC.
now = datetime.now(timezone.utc)Aware from the start.
print((now - aware).days >= 0)True: aware minus aware works; naive minus aware would raise TypeError.
Your turn
The current moment, aware, in UTC.
now = datetime.now()
Solve one with the tests running
The trap
datetime.utcnow() returns a naive value that merely happens to be UTC. It is deprecated for that reason; use datetime.now(timezone.utc).