'When to use datetime.utcnow() or datetime.now(tz=pytz.utc).replace(tzinfo=None)

I would like to understand when I should be using

datetime.now(tz=pytz.utc).replace(tzinfo=None)

as opposed to simply

datetime.utcnow()

Will the latter not take into account e.g. daylight savings?



Solution 1:[1]

You should never use datetime.utcnow() as it gives you a naïve timestamp that you can shoot yourself in the foot with. If you really want a naïve timestamp, make it explicit using your first option. now() takes the tz parameter (which you should always supply, to avoid using the host TZ). But utcnow() obviously doesn't provide that. So it is doomed.

For example, let's say you have a UTC timestamp, and you want to convert it to the local time in Mexico City:

my_timestamp.astimezone(pytz.timezone("America/Mexico_City"))

Looks fine, right? Nope, check this out:

>>> datetime.utcnow()
datetime.datetime(2021, 3, 29, 21, 40, 44, 329559)
>>> datetime.utcnow().astimezone(pytz.timezone("America/Mexico_City"))
datetime.datetime(2021, 3, 29, 21, 40, 44, 329559, tzinfo=<DstTzInfo 'America/Mexico_City' CST-1 day, 18:00:00 STD>)

As you can see, astimezone will just tack on the tz if you give it a naïve timestamp, without adjusting the actual time as expected. (if you didn't want to adjust, you'd have used .replace)

It's super confusing, and you don't run into problems like this if you just make sure you have no naïve timestamps. You can have them in your external APIs, if you like, but tack on a timezone when they enter the system.

To summarize: always use datetime.now(tz=some_tz).

Solution 2:[2]

To quote Paul Ganssle's article Stop using utcnow and utcfromtimestamp

[Don't] use utcnow() or utcfromtimestamp() simply because it's the wrong abstraction.

[...]

The reason that we cannot simply change utcnow() into an alias for now(timezone.utc) in the standard library is that would change the semantics of how those datetimes are treated by their consumers

IIRC, he contributed quite a bit to cpython (the core of Python) around datetime.

Hence: Don't use datetime.utcnow()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Martin Thoma