Why Nostr? What is Njump?
2024-05-31 20:23:52

Fabio Manganiello on Nostr: What a mess with #Python’s utcnow deprecation.datetime.datetime.utcnow() has been ...

What a mess with #Python’s utcnow deprecation.datetime.datetime.utcnow()

has been deprecated since Python 3.12. And I see why. I’ve always wondered why that method for some reason returned a timezone-naive datetime. Like if I’m asking for UTC, can’t you just set tzinfo to UTC, before I accidentally do a comparison with a datetime.datetime.now() (which is also timezone-naive) a couple of lines down and suddenly end up comparing a timestamp in L.A. with one in London?

The officially suggested alternative is to go for a datetime.datetime.now(datetime.UTC) instead, so explicitly set the UTC timezone if you need a monotonous datetime object.

It’s a sensible implementation that should already have been implemented years ago.

Except that datetime.UTC is a macro introduced only in Python 3.11. On older versions:<code>&gt;&gt;&gt; import datetime
&gt;&gt;&gt; datetime.UTC
Traceback (most recent call last):
File "&lt;stdin&gt;", line 1, in &lt;module&gt;
AttributeError: module 'datetime' has no attribute 'UTC'</code>

So the officially supported solution actually only works with Python versions released since October 2022. They could have at least suggested datetime.tzinfo.utc, as that one at least has been around for a while.

But the biggest issue is how badly it breaks back-compatibility with everything that has been written (and stored) before.

Take this code for example:<code>import datetime as dt

...

token = SessionToken(...)
token.expires_at = (
dt.datetime.utcnow() + dt.timedelta(days=365)
)

db.save(token)

...

if token.expires_at &lt; dt.datetime.utcnow():
raise ExpiredSession(...)</code>

You’ve been running this code for a while, you’ve created a bunch of users, and since you used utcnow all those timestamps have been stored as offset-naive UTC.

Now you modify all the references of utcnow with now(dt.UTC). What happens?

Well, if your code was running with timestamps that are generated on the fly, everything should go ok. It’s a tz-aware to tz-aware comparison. But what happens when you load from the db your token that was saved with the previous, tz-naive utcnow implementation? Well, your code breaks all of a sudden:<code>TypeError: can't compare offset-naive and offset-aware datetimes</code>

I’m not sure if everyone within the community is already aware of the consequences of the new implementation, and that migrating to Python >= 3.12 should be considered a breaking change - especially if your code deals with persisted datetime objects.
Author Public Key
npub1s9uc08n58mxqk5umvapqulwzng0sja635q86r36d8n4rr9r9ygaskjdnmu