'Azure Python Function datetime expression

May I know the difference between datetime.datetime.utcnow() and datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)?

The second one is from the Azure Function doc, it was already specify with UTC time via .utcnow(), is it necessary to add .replace(tzinfo=datetime.timezone.utc) to specify the UTC time again? Per my test, they output the same time.



Solution 1:[1]

Looking at the object representation of what you get from the two expressions:

import datetime

dt1 = datetime.datetime.utcnow()
dt2 = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)

print(repr(dt1))
# datetime.datetime(2022, 5, 18, 7, 33, 42, 993707)

print(repr(dt2))
# datetime.datetime(2022, 5, 18, 7, 33, 42, 993707, tzinfo=datetime.timezone.utc)

The first expressions gives you a datetime object with attributes set to current UTC date/time. But the object is naive, meaning it is not specified to be UTC, the tzinfo is not set. The second expressions changes that, by replacing the tzinfo to be UTC. That has consequences for .isoformat output (it's used in the Azure docs):

print(dt1.isoformat())
# 2022-05-18T07:33:42.993707

print(dt2.isoformat())
# 2022-05-18T07:33:42.993707+00:00

The second expressions has a UTC offset attached, the first one hasn't.

Why care?

Python will treat naive datetime as local time. That can be pretty confusing if you expect UTC because you used utcnow... Setting the tzinfo right away is the better option in most contexts. A concise expression giving you the same result whilst avoiding utcnow would be

datetime.datetime.now(datetime.timezone.utc)

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