All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.py.rules.python.S6903.html Maven / Gradle / Ivy

The newest version!

This rule raises an issue when the functions datetime.datetime.utcnow or datetime.datetime.utcfromtimestamp are used.

Why is this an issue?

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.

How to fix it

To fix this issue, prefer the usage of a timezone-aware datetime.

Code examples

Noncompliant code example

from datetime import datetime

datetime.utcnow() # Noncompliant

timestamp = 1571595618.0
datetime.utcfromtimestamp(timestamp) # Noncompliant

Compliant solution

from datetime import datetime, timezone

datetime.now(timezone.utc) # Compliant

timestamp = 1571595618.0
datetime.fromtimestamp(timestamp, timezone.utc) # Compliant

Resources

Documentation

Articles & blog posts





© 2015 - 2025 Weber Informatics LLC | Privacy Policy