Time zone aware datetimes Medium

Naive datetime objects are treated by many datetime methods as local times and might cause time zone related issues.

Detector ID
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1def datetime_noncompliant():
2    from datetime import datetime
3    # Noncompliant: datetime method does not specify timezone,
4    # resulting in time zone related issues.
5    return datetime.now()

Compliant example

1def datetime_compliant():
2    from datetime import datetime, timezone
3    # Compliant: datetime method specifies the time zone,
4    # avoiding the time zone related issues.
5    return datetime.now(tz=timezone.utc)