Sub topic 3
Naive and aware datetimes
This chapter assumes you can create datetime objects and use timedelta, and that you know what UTC and a UTC offset are. It covers how datetime decides whether a value is tied to a real moment, which operations break when you mix the two kinds, and how to move between them safely.
Two kinds of datetime
Every datetime object is one of two kinds.
- A naive datetime has no time zone information. It is only a calendar date and a wall-clock reading, such as "2026-01-01 12:00". It does not say where in the world that is.
- An aware datetime carries a time zone, through its
tzinfoattribute. It identifies one exact moment on the global timeline.
The distinction lives in tzinfo and utcoffset():
from datetime import datetime, timezone
naive = datetime(2026, 1, 1, 12, 0)
aware = datetime(2026, 1, 1, 12, 0, tzinfo=timezone.utc)
print(naive.tzinfo)
print(aware.tzinfo)
print(naive.utcoffset())
print(aware.utcoffset())This prints None, UTC, None, and 0:00:00.
The Python documentation defines "aware" with two conditions. Both must hold: dt.tzinfo is not None, and dt.tzinfo.utcoffset(dt) does not return None. A small helper makes this check reusable:
from datetime import datetime, timezone
def is_aware(dt: datetime) -> bool:
return dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None
print(is_aware(datetime(2026, 1, 1)))
print(is_aware(datetime(2026, 1, 1, tzinfo=timezone.utc)))This prints False and then True. A tzinfo whose utcoffset() returns None is rare. Custom tzinfo classes can do it, and such a datetime counts as naive.
What a naive datetime means
A naive datetime is a label without a context. The value datetime(2026, 1, 1, 12, 0) can mean noon in Tokyo, noon in London, or noon on a server in an unknown zone. Python does not record which one.
Naive datetimes are not always wrong. They suit values that really are zone-free:
- A recurring local schedule, such as "the shop opens at 09:00 wherever the shop is".
- Arithmetic on calendar labels where no real instant is involved.
- Quick scripts that run in one place and never exchange times with anything else.
Once a value crosses a boundary, the missing context becomes a bug. Boundaries include a database, an API, another server, and a user in a different country. The receiver has to guess what the zone was, and the guess is often wrong.
Where naive datetimes come from
Many naive values are created by accident. These calls return naive results:
| Expression | Result |
|---|---|
| `datetime(2026, 1, 1)` | Naive, because no `tzinfo` was given |
| `datetime.now()` | Naive, holding the system's local time |
| `datetime.fromtimestamp(ts)` | Naive, converted to system local time |
| `datetime.utcnow()` | Naive, holding UTC values with no UTC label |
| `datetime.utcfromtimestamp(ts)` | Naive, with the same problem |
| `datetime.strptime("2026-01-01", "%Y-%m-%d")` | Naive, unless the format includes `%z` |
| `datetime.fromisoformat("2026-01-01T12:00")` | Naive, because the string has no offset |
datetime.utcnow() and datetime.utcfromtimestamp() are deprecated as of Python 3.12 because of this trap. The values look like UTC, but nothing marks them as UTC. If you later call a method that treats naive values as local time, the result is silently wrong. Pass a zone instead:
from datetime import datetime, timezone
now_utc = datetime.now(timezone.utc)
print(now_utc.tzinfo)This prints UTC.
These calls return aware results:
datetime.now(tz)for any time zone objecttz.datetime.fromtimestamp(ts, tz).datetime.fromisoformat(...)on a string that includes an offset, such as+00:00.datetime.strptime(...)with a%zdirective.- Any constructor call with
tzinfo=set.
Python 3.11 and later also accept a trailing Z in fromisoformat. Python 3.9 and 3.10 raise ValueError on it, so replace Z with +00:00 first if you support those versions.
What happens when you mix them
Python refuses to guess how a naive value relates to an aware one. This is deliberate, because a guess would be right on some machines and wrong on others.
from datetime import datetime, timezone
naive = datetime(2026, 1, 1)
aware = datetime(2026, 1, 1, tzinfo=timezone.utc)
try:
print(naive < aware)
except TypeError as e:
print(e)This prints can't compare offset-naive and offset-aware datetimes.
The behavior differs by operation, and one case does not raise at all:
| Operation | naive with naive | aware with aware | naive with aware |
|---|---|---|---|
| `<`, `<=`, `>`, `>=` | Compares labels | Compares instants | `TypeError` |
| `==`, `!=` | Compares labels | Compares instants | Returns `False` and `True`, no error |
| `a - b` | `timedelta` | `timedelta` | `TypeError` |
| `a + timedelta` | Works | Works | Not applicable, since only one datetime is involved |
| `sorted(list)` or `min`/`max` | Works | Works | `TypeError` if the list mixes kinds |
Equality between a naive and an aware value is the dangerous case. naive == aware quietly returns False, even when the labels look identical. A filter like if event.start == deadline then fails with no error message. If a comparison that should sometimes be true never is, check whether one side is naive.
Aware datetimes compare by instant
Two aware datetimes can have different offsets and still be equal. Python converts both to UTC before comparing or subtracting:
from datetime import datetime, timedelta, timezone
minus_five = timezone(timedelta(hours=-5))
a = datetime(2026, 11, 26, 9, 0, tzinfo=minus_five)
b = datetime(2026, 11, 26, 14, 0, tzinfo=timezone.utc)
print(a == b)
print(b - a)
print(a < b + timedelta(seconds=1))This prints True, 0:00:00, and True. The two values describe the same instant even though their clocks read different hours. The timezone(timedelta(...)) form creates a fixed-offset zone. The next chapter covers it in detail.
Moving between naive and aware
Two methods change the zone information, and they do different jobs. Mixing them up is the most common mistake in this area.
replace(tzinfo=...)attaches or swaps the label. It keeps the clock fields and changes which instant the value names.astimezone(tz)converts. It keeps the instant and changes the clock fields to match the new zone.
from datetime import datetime, timedelta, timezone
est = timezone(timedelta(hours=-5))
utc_time = datetime(2026, 11, 26, 14, 0, tzinfo=timezone.utc)
converted = utc_time.astimezone(est)
relabeled = utc_time.replace(tzinfo=est)
print(converted)
print(relabeled)
print(converted == utc_time)
print(relabeled == utc_time)The output is:
2026-11-26 09:00:00-05:00
2026-11-26 14:00:00-05:00
True
Falseconverted is the same moment shown on a clock five hours behind. relabeled is a different moment, five hours later than the original, because 14:00 at offset -05:00 equals 19:00 UTC.
Use each method in its own situation:
- You know what zone a naive value was recorded in. Use
replace(tzinfo=that_zone)once, at the point where the data enters your program. This is the correct use ofreplace, because you are supplying missing information. - You already have an aware value and want to display it elsewhere. Use
astimezone(other_zone). - You need a naive value for a legacy API. Convert to the zone the API expects, then call
replace(tzinfo=None)to drop the label.
The implicit conversion on naive values
astimezone() also works on a naive datetime. Python then assumes the value is in the system's local time zone:
from datetime import datetime, timezone
local_guess = datetime(2026, 11, 26, 9, 0).astimezone(timezone.utc)
print(local_guess)The output depends on the machine's configured zone. A laptop in New York prints 2026-11-26 14:00:00+00:00, and a server already set to UTC prints 2026-11-26 09:00:00+00:00. Code that works on your machine and fails in a container is often relying on this behavior.
Common errors and how to find them
TypeError: can't compare offset-naive and offset-aware datetimes. One operand came from datetime.now(), utcnow(), or a string without an offset. The other came from an aware source, such as a database driver, an API client, or now(timezone.utc). Print repr(value) for both, because the repr shows tzinfo=... when it is set. Then fix the source of the naive one, instead of stripping the zone from the aware one.
TypeError: can't subtract offset-naive and offset-aware datetimes. This is the same cause, met during subtraction. A typical case is datetime.now(timezone.utc) - record.created_at, where the library returned a naive created_at.
A comparison that is always false. This is the silent equality case from the table above. Check is_aware() on both sides.
A time that is off by a fixed number of hours. Someone used replace(tzinfo=...) where astimezone(...) was needed, or the reverse. Compare against the earlier example: if the clock fields stayed the same but the offset changed, replace ran. If the clock fields changed along with the offset, astimezone ran.
Times that shift when the code moves to another machine. A naive value was converted with astimezone() or timestamp(), and Python assumed the local zone. Calling .timestamp() on a naive datetime has the same dependence on the machine's configured zone.
A boundary function
A practical habit is to check at the edges of your program that every datetime is aware. A small function can enforce this where data enters:
from datetime import datetime, timezone
def require_aware(dt: datetime) -> datetime:
if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None:
raise ValueError(f"naive datetime not allowed: {dt!r}")
return dt.astimezone(timezone.utc)
print(require_aware(datetime(2026, 11, 26, 9, 0, tzinfo=timezone.utc)))
try:
require_aware(datetime(2026, 11, 26, 9, 0))
except ValueError as e:
print(e)The first call prints 2026-11-26 09:00:00+00:00. The second prints naive datetime not allowed: datetime.datetime(2026, 11, 26, 9, 0). Rejecting naive input loudly is better than guessing a zone for it. The final rules chapter builds on this idea of normalizing at the boundary.
Summary
- Naive means
tzinfoisNone(or itsutcoffset()returnsNone). Aware means it names a real offset. - Ordering and subtraction between the two kinds raise
TypeError. Equality silently returnsFalse. replace(tzinfo=...)changes the label and the instant.astimezone(...)changes the label and keeps the instant.- Calling
astimezone()ortimestamp()on a naive value assumes the machine's local zone, which varies between machines. - Avoid
utcnow()andutcfromtimestamp(). Usedatetime.now(timezone.utc)anddatetime.fromtimestamp(ts, timezone.utc).
Exercise
A function receives start = datetime(2026, 6, 1, 8, 0, tzinfo=timezone.utc) and deadline = datetime(2026, 6, 1, 8, 0). The check start == deadline returns False, and start < deadline raises an exception. Explain why each happens, and write one line that makes deadline comparable if you know it was recorded in UTC.
Show answer
The two values have identical clock fields, but start is aware and deadline is naive. Equality between a naive and an aware datetime always returns False without raising. Ordering comparisons raise TypeError because Python will not guess the naive value's zone. Since you know the zone, supply it with deadline = deadline.replace(tzinfo=timezone.utc). After that, start == deadline is True. Using astimezone here would be wrong, because it would treat the naive value as system local time.
Exercise
What do a and b print, and are they equal to base?
base = datetime(2026, 11, 26, 14, 0, tzinfo=timezone.utc)
est = timezone(timedelta(hours=-5))
a = base.astimezone(est)
b = base.replace(tzinfo=est)
print(a, b)
Show answer
a prints 2026-11-26 09:00:00-05:00 and b prints 2026-11-26 14:00:00-05:00. a == base is True, because astimezone keeps the same instant and only changes the displayed clock. b == base is False, because replace kept 14:00 and relabeled it as offset -05:00, which is 19:00 UTC, five hours after base.