org.sonar.l10n.py.rules.python.S6890.html Maven / Gradle / Ivy
This rule raises an issue when using the pytz
library on a codebase using Python 3.9 or later.
Why is this an issue?
In Python 3.9 and later, the zoneinfo
module is the recommended tool for handling timezones, replacing the pytz
library.
This recommendation is based on several key advantages.
First, zoneinfo
is part of Python’s standard library, making it readily available without needing additional installation, unlike
pytz
.
Second, zoneinfo
integrates seamlessly with Python’s datetime module. You can directly use zoneinfo
timezone objects when
creating datetime
objects, making it more intuitive and less error-prone than pytz
, which requires a separate localize
method for this purpose.
Third, zoneinfo
handles historical timezone changes more accurately than pytz
. When a pytz
timezone object
is used, it defaults to the earliest known offset, which can lead to unexpected results. zoneinfo
does not have this issue.
Lastly, zoneinfo
uses the system’s IANA time zone database when available, ensuring it works with the most up-to-date timezone data.
In contrast, pytz
includes its own copy of the IANA database, which may not be as current.
In summary, zoneinfo
offers a more modern, intuitive, and reliable approach to handling timezones in Python 3.9 and later, making it
the preferred choice over pytz
.
How to fix it
To fix this is issue use a zoneinfo
timezone object when constructing a datetime
instead of the pytz
library.
Code examples
Noncompliant code example
from datetime import datetime
import pytz
dt = pytz.timezone('America/New_York'').localize(datetime(2022, 1, 1)) # Noncompliant: the localize method is needed to avoid bugs (see S6887)
Compliant solution
from datetime import datetime
from zoneinfo import ZoneInfo
dt = datetime(2022, 1, 1, tzinfo=ZoneInfo('America/New_York')) # OK: timezone object can be used safely through the datetime constructor
Resources
Documentation
Related rules
- {rule:python:S6887} - pytz.timezone should not be passed to the datetime.datetime constructor