tzlocal

repository·master·Indexed 42 days ago

https://github.com/regebro/tzlocal

A Python module for detecting the local system's IANA time zone name or retrieving a tzinfo object. Version 5.0+ returns zoneinfo.ZoneInfo objects. It provides utilities such as get_localzone(), get_localzone_name(), and reload_localzone() to bridge gaps in standard library modules like pytz and zoneinfo.

Tokens
2K
Snippets
13
Records
15
Agent score
52%

What's inside tzlocal

  1. Version compatibility: pytz vs zoneinfo

    master

    The return type of tzlocal has changed across major versions:

    • Version 3.0: Returned zoneinfo objects.
    • Version 4.0: Restored partial compatibility for pytz users via a shim.
    • Version 5.0+: Removes the pytz shim. It only returns zoneinfo objects.

    If your application strictly requires pytz objects, you must use version 4.0.

  2. Fix timezone issues in Docker

    master

    Docker images often have broken timezone configurations, which may cause tzlocal to issue warnings about incorrect configurations or mismatched offsets.

    To resolve this, set the TZ environment variable in your Docker configuration to your desired timezone (typically matching your host machine).

  3. Debug timezone configuration issues

    master

    If tzlocal returns unexpected results, enable DEBUG logging to see which configuration files (like /etc/timezone or /etc/localtime) are being detected and what their contents are.

    import logging
    logging.basicConfig(level="DEBUG")
    import tzlocal
    
    tzlocal.get_localzone()
  4. Create and convert timezone-aware datetimes

    master

    You can use the tzinfo object returned by get_localzone() to create aware datetime objects and then convert them to other timezones using astimezone().

    from datetime import datetime
    from tzlocal import get_localzone
    from zoneinfo import ZoneInfo
    
    # 1. Get local timezone
    tz = get_localzone()
    
    # 2. Create a local aware datetime
    dt = datetime(2015, 4, 10, 7, 22, tzinfo=tz)
    
    # 3. Convert to another timezone
    eastern = ZoneInfo('US/Eastern')
    converted_dt = dt.astimezone(eastern)
  5. Get the local timezone object with get_localzone()

    master

    Use get_localzone() to retrieve a tzinfo object representing your system's local time zone. In version 5.0+, this returns a zoneinfo.ZoneInfo object. This is useful for creating timezone-aware datetime objects or performing conversions between timezones.

    Note: On some Unix systems, if a specific timezone name is not configured, get_localzone() may still succeed by providing a functional tzinfo object even if the name is unavailable.

    from tzlocal import get_localzone
    
    tz = get_localzone()
    # Returns a zoneinfo.ZoneInfo object, e.g., zoneinfo.ZoneInfo(key='Europe/Warsaw')
  6. Get the local timezone name with get_localzone_name()

    master

    Use get_localzone_name() if you only need the IANA timezone name as a string (e.g., 'Europe/Warsaw') rather than a full tzinfo object.

    Warning: On Unix systems, this function may raise an error if the system does not have a timezone name explicitly configured in files like /etc/timezone. If you need a fallback that succeeds even without a configured name, use get_localzone() instead.

    from tzlocal import get_localzone_name
    
    name = get_localzone_name()
    # Returns a string, e.g., "Europe/Warsaw"
  7. Validate timezone configuration with assert_tz_offset()

    master

    Use assert_tz_offset(tz, error=True) to verify that the provided timezone's offset matches the current system's timezone offset. This is useful for detecting misconfigurations, such as an incorrect /etc/timezone file in systemd distributions.

    • If error=True (default): Raises a ValueError if the offsets do not match (difference > 60 seconds).
    • If error=False: Emits a warnings.warn() instead of raising an exception.

    The comparison allows for a 60-second margin of error to account for minor discrepancies.

    from tzlocal.utils import assert_tz_offset
    import zoneinfo
    
    tz = zoneinfo.ZoneInfo("UTC")
    # This will raise ValueError if the system offset differs from UTC by more than 60s
    assert_tz_offset(tz, error=True)
    
    # This will only issue a warning if they differ
    assert_tz_offset(tz, error=False)
  8. Get the local timezone name on Windows

    master

    Use get_localzone_name() to retrieve the zoneinfo timezone name that matches the current Windows-configured timezone.

    On Windows, this function performs a lookup in the registry (SYSTEM\CurrentControlSet\Control\TimeZoneInformation). If Daylight Saving Time (DST) is explicitly disabled in the Windows configuration, the function returns an Etc/GMT formatted string (e.g., Etc/GMT+5) instead of a standard timezone name to ensure the offset is correctly represented.

    from tzlocal import win32
    
    name = win32.get_localzone_name()
    print(f"Local timezone name: {name}")
  9. Reload the cached local timezone

    master

    If the system's timezone configuration has changed during the execution of your program, call reload_localzone() to clear the internal cache and fetch the updated timezone information from the Windows registry.

    from tzlocal import win32
    
    # If the system timezone changed
    tz = win32.reload_localzone()
    print(f"Updated timezone: {tz}")
  10. Get a timezone's offset with get_tz_offset()

    master

    Use get_tz_offset(tz) to retrieve the UTC offset of a given timezone in seconds. It uses the built-in datetime.utcoffset() method to calculate the total seconds.

    from tzlocal.utils import get_tz_offset
    import zoneinfo
    
    tz = zoneinfo.ZoneInfo("America/New_York")
    offset_seconds = get_tz_offset(tz)
  11. Reload the local timezone with reload_localzone()

    master

    Use reload_localzone() to force the library to re-detect the system's local timezone. This is useful if the system timezone has changed during the execution of a process.

    from tzlocal import reload_localzone
    
    # Force re-detection
    reload_localzone()