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 timezone-naive) in another method and suddenly end up comparing a timestamp in L.A. with one in London, without any interpreter mechanisms to differentiate between the two?
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>>>> import datetime
>>> datetime.UTC
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
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 < 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. Sometimes you have to break eggs in order to make an omelette, I guess.
programming group (npub1k55…6pef)