Skip to content

Aware datetime For UTC

Sourcery suggestion id: aware-datetime-for-utc

Description

For getting the current time in UTC, use an aware datetime object with the timezone explicitly set to UTC.

Before

from datetime import datetime

this_moment_utc = datetime.utcnow()

After

from datetime import datetime, timezone

this_moment_utc = datetime.now(timezone.utc)

Explanation

The documentation for the datetime.datetime.utcnow() function provides an excellent explanation why we should prefer to use aware datetime objects:

Warning: Because naive datetime objects are treated by many datetime methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling datetime.now(timezone.utc).

Back to top