This rule raises an issue when the functions datetime.datetime.utcnow or datetime.datetime.utcfromtimestamp are used.
Python’s datetime API provide several different ways to create datetime objects. One possibility is the to use
datetime.datetime.utcnow or datetime.datetime.utcfromtimestamp functions. The issue with these two functions is they are not
time zone aware, even if their name would suggest otherwise.
Using these functions could cause issue as they may not behave as expected, for example:
from datetime import datetime timestamp = 1571595618.0 date = datetime.utcfromtimestamp(timestamp) date_timestamp = date.timestamp() assert timestamp == date_timestamp
This assertion will fail if the system locale is not set to UTC. For this reason these 2 functions are deprecated in Python 3.12.
To fix this issue, prefer the usage of a timezone-aware datetime.
from datetime import datetime datetime.utcnow() # Noncompliant timestamp = 1571595618.0 datetime.utcfromtimestamp(timestamp) # Noncompliant
from datetime import datetime, timezone datetime.now(timezone.utc) # Compliant timestamp = 1571595618.0 datetime.fromtimestamp(timestamp, timezone.utc) # Compliant