Skip to content

fix: Replace pytz with zoneinfo (Python 3.9+ standard)#317

Merged
GuyKh merged 2 commits intomainfrom
fix/replace-pytz-with-zoneinfo
Feb 15, 2026
Merged

fix: Replace pytz with zoneinfo (Python 3.9+ standard)#317
GuyKh merged 2 commits intomainfrom
fix/replace-pytz-with-zoneinfo

Conversation

@GuyKh
Copy link
Owner

@GuyKh GuyKh commented Feb 15, 2026

User description

Summary

Replace deprecated pytz library with Python 3.9+'s built-in zoneinfo module.

Changes

  • Replace import pytz with from zoneinfo import ZoneInfo in commons.py
  • Add localize_datetime() helper function for timezone-aware datetime conversion
  • Update all .localize() calls in coordinator.py and sensor.py to use the new helper
  • This removes the external pytz dependency

Why

  • pytz is deprecated in favor of the built-in zoneinfo module (PEP 615)
  • Python 3.9+ has native timezone support that's more reliable
  • Reduces external dependencies

Compatibility

  • Project already targets Python 3.12 (per .ruff.toml)
  • zoneinfo has been available since Python 3.9

PR Type

Bug fix, Enhancement


Description

  • Replace deprecated pytz library with Python 3.9+ built-in zoneinfo module

  • Add localize_datetime() helper function for consistent timezone handling

  • Update all timezone localization calls across coordinator and sensor modules

  • Remove external pytz dependency, reducing project dependencies


Diagram Walkthrough

flowchart LR
  A["pytz library<br/>deprecated"] -->|"replace with"| B["zoneinfo.ZoneInfo<br/>Python 3.9+ built-in"]
  B -->|"used by"| C["localize_datetime()<br/>helper function"]
  C -->|"called in"| D["coordinator.py<br/>sensor.py"]
  D -->|"result"| E["Timezone-aware<br/>datetime objects"]
Loading

File Walkthrough

Relevant files
Enhancement
commons.py
Replace pytz with zoneinfo and add helper                               

custom_components/iec/commons.py

  • Replace import pytz with from zoneinfo import ZoneInfo
  • Update TIMEZONE constant to use ZoneInfo("Asia/Jerusalem") instead of
    pytz.timezone()
  • Add new localize_datetime() helper function that safely localizes
    naive datetimes to the IEC timezone
  • Import datetime class for type hints in the new helper function
+17/-4   
coordinator.py
Update coordinator to use localize_datetime helper             

custom_components/iec/coordinator.py

  • Import new localize_datetime helper function from commons module
  • Replace 6 instances of TIMEZONE.localize() calls with
    localize_datetime() function
  • Updates occur in _update_data(), _insert_statistics(), and
    _estimate_bill() methods
  • Maintains same timezone localization behavior with new zoneinfo-based
    implementation
+8/-8     
sensor.py
Update sensor to use localize_datetime helper                       

custom_components/iec/sensor.py

  • Import new localize_datetime helper function from commons module
  • Replace 3 instances of TIMEZONE.localize() calls with
    localize_datetime() function
  • Updates occur in sensor value functions for daily readings and monthly
    consumption
  • Maintains consistent timezone handling across sensor definitions
+4/-4     

- Replace deprecated pytz library with built-in zoneinfo
- Add localize_datetime() helper for timezone-aware datetimes
- Update all .localize() calls to use the new helper
- This change removes the pytz dependency
@qodo-code-review
Copy link

ⓘ You are approaching your monthly quota for Qodo. Upgrade your plan

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Timezone edge cases: The new localize_datetime() assigns tzinfo via dt.replace(tzinfo=TIMEZONE) which may
mishandle DST/ambiguous/non-existent times and may misinterpret naive
datetime.now()/fromtimestamp() values depending on the runtime's local timezone
configuration.

Referred Code
def localize_datetime(dt: datetime) -> datetime:
    """Localize a datetime to the IEC timezone.

    Args:
        dt: A naive datetime to localize.

    Returns:
        A timezone-aware datetime in Asia/Jerusalem timezone.
    """
    if dt.tzinfo is not None:
        return dt
    return dt.replace(tzinfo=TIMEZONE)

Learn more about managing compliance generic rules or creating your own custom rules

Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review
Copy link

ⓘ You are approaching your monthly quota for Qodo. Upgrade your plan

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible issue
Use timezone-aware datetime object creation

Replace localize_datetime(datetime.now()) with datetime.now(TIMEZONE) to
correctly create a timezone-aware datetime object, avoiding potential timezone
mismatches.

custom_components/iec/coordinator.py [526]

-localized_today = localize_datetime(datetime.now())
+localized_today = datetime.now(TIMEZONE)
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies a critical bug where using datetime.now() with the new helper function can lead to incorrect timestamps if the system timezone is not the target timezone, and proposes the correct fix.

High
Correctly convert timestamp to timezone-aware datetime

Replace localize_datetime(datetime.fromtimestamp(last_stat_time)) with
datetime.fromtimestamp(last_stat_time, tz=TIMEZONE) to correctly convert a
timestamp to a timezone-aware datetime.

custom_components/iec/coordinator.py [1001-1007]

 new_readings: list[PeriodConsumption] = filter(
     lambda reading: (
         reading.interval
-        >= localize_datetime(datetime.fromtimestamp(last_stat_time))
+        >= datetime.fromtimestamp(last_stat_time, tz=TIMEZONE)
     ),
     readings.meter_list[0].period_consumptions,
 )
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies a critical bug where converting a timestamp to a naive datetime and then localizing it can result in an incorrect time, and it provides the correct, direct conversion method.

High
General
Use timezone-aware now() in sensor

Replace localize_datetime(datetime.now()) with datetime.now(TIMEZONE) within a
timedelta calculation to ensure correct timezone-aware arithmetic.

custom_components/iec/sensor.py [224-232]

 value_fn=lambda data: (
     _get_reading_by_date(
         data[DAILY_READINGS_DICT_NAME][...],
-        localize_datetime(datetime.now()) - timedelta(days=1),
+        datetime.now(TIMEZONE) - timedelta(days=1),
     ).consumption
 )

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies a critical bug where using datetime.now() with the new helper function can lead to incorrect timestamps if the system timezone is not the target timezone, and proposes the correct fix.

High
  • More

@GuyKh GuyKh merged commit 4c0f539 into main Feb 15, 2026
5 checks passed
@GuyKh GuyKh deleted the fix/replace-pytz-with-zoneinfo branch February 15, 2026 13:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant