DEV Community

Cover image for datetime.utcnow() is deprecated since Python 3.12. It was a trap long before that.
Versyka
Versyka

Posted on AI-assisted

datetime.utcnow() is deprecated since Python 3.12. It was a trap long before that.

Python 3.12 deprecated utcnow(). Your timestamps were already wrong. The warning is new; the bug is old. Since 3.12, these emit a DeprecationWarning:

datetime.utcnow()
datetime.utcfromtimestamp(ts)
Enter fullscreen mode Exit fullscreen mode

What was wrong with them

Both return a naive datetime: the clock reading in UTC, with tzinfo=None. The value doesn't say it's UTC. Two things follow:

>>> from datetime import datetime, timezone
>>> datetime.utcnow() < datetime.now(timezone.utc)
TypeError: can't compare offset-naive and offset-aware datetimes
Enter fullscreen mode Exit fullscreen mode

And anything that later treats a naive datetime as local time shifts it by your server's UTC offset. That's the classic "the nightly job ran five hours late" bug, and it only shows up on servers that aren't set to UTC.

The replacements

  from datetime import datetime, timezone

- now = datetime.utcnow()
+ now = datetime.now(timezone.utc)

- created = datetime.utcfromtimestamp(ts)
+ created = datetime.fromtimestamp(ts, timezone.utc)
Enter fullscreen mode Exit fullscreen mode

Both return aware datetimes, with UTC attached. Comparisons, arithmetic and .isoformat() (which now ends in +00:00) all behave.

The part people miss: stored values

If your database or files already hold naive UTC values, mixing them with new aware ones raises the same TypeError. Pick one:

  • Make old values aware when you read them: value.replace(tzinfo=timezone.utc).
  • Or migrate the column to a timezone-aware type once, then switch the code.

And check anything that serialises timestamps: the +00:00 suffix can break a strict parser on the other end.

Make the next one loud

pytest -W error::DeprecationWarning
Enter fullscreen mode Exit fullscreen mode

Every deprecated call your tests touch now fails with a traceback pointing at your line, so the next change like this shows up long before the release that removes it.

Versyka finds every call a deprecation like this touches and opens the change as one tested pull request, but grep -rn "utcnow\|utcfromtimestamp" . gets you the list in a second.

How many utcnow() calls does your codebase have? Guess first, then grep.

Top comments (0)