2024-08-26 16:00:15 +02:00

49 lines
1.3 KiB
Plaintext

This rule raises an issue when trying to perform comparison or arithmetic operations between `offset-naive` and `offset-aware` Datetimes.
== Why is this an issue?
`datetime.datetime` and `datetime.time` objects may be categorized as "aware" or "naive" depending on whether or not they include timezone information.
Comparison or arithmetic operations between `offset-naive` and `offset-aware` datetimes raise a `TypeError`.
== How to fix it
Perform comparison or arithmetic operations only between offset-naive or only between offset-aware Datetimes.
=== Code examples
==== Noncompliant code example
[source,python,diff-id=1,diff-type=noncompliant]
----
from datetime import datetime
from pytz import timezone
def compare_tz():
dt1 = datetime.now(tz=timezone('America/New_York'))
dt2 = datetime.now()
if dt1 < dt2: # Noncompliant: TypeError: can't compare offset-naive and offset-aware datetimes
...
----
==== Compliant solution
[source,python,diff-id=1,diff-type=compliant]
----
from datetime import datetime
from pytz import timezone
def compare_tz():
dt1 = datetime.now(tz=timezone('America/New_York'))
dt2 = datetime.now(timezone.utc)
if dt1 < dt2:
...
----
== Resources
=== Documentation
* Python documentation - https://docs.python.org/3/library/datetime.html#aware-and-naive-objects[Aware and Naive Objects]