pytz Documentation

repository·master·Indexed 16 days ago

https://github.com/stub42/pytz

A Python library that brings the IANA timezone database into Python to provide accurate, cross-platform timezone calculations. It includes tools for localizing naive datetimes, handling Daylight Saving Time (DST) transitions via normalize(), and managing ambiguous or non-existent times. The library provides a UTC singleton, fixed-offset timezones via FixedOffset(), and mappings for ISO 3166 country codes to timezones and country names.

Tokens
5.6K
Snippets
23
Records
30
Agent score
64%

What's inside pytz

  1. Overview of pytz

    master

    pytz brings the IANA timezone database into Python, enabling accurate and cross-platform timezone calculations.

    Note: The root directory contains generated code. For the actual source code and primary documentation, refer to the src/ directory.

  2. Understand pytz limitations and precision

    master

    When using pytz, be aware of the following technical constraints:

    • Offset Rounding: Offsets from UTC are rounded to the nearest whole minute. This means for certain historical timezones (e.g., Europe/Amsterdam prior to 1937), the time may be off by up to 30 seconds due to historical limitations in the Python datetime library.
    • Data Source: pytz is a direct translation of the Olson timezone database. If you encounter incorrect timezone definitions, they must be addressed at the IANA source rather than within pytz itself.
  3. Use UTC for internal timezone representation

    master

    The recommended best practice for avoiding timezone ambiguity and errors in date arithmetic is to use UTC for all internal representations. pytz provides a highly optimized UTC implementation.

    You can access the UTC timezone via pytz.utc, pytz.UTC, or pytz.timezone('UTC').

    import pytz
    from datetime import datetime
    
    # Accessing UTC
    utc = pytz.utc
    
    # Creating a UTC datetime
    dt = datetime(2005, 3, 1, 14, 13, 21, tzinfo=utc)
  4. How to handle daylight saving time transitions with normalize()

    master

    When performing date arithmetic on local times that cross Daylight Saving Time (DST) boundaries, the resulting datetime may have an incorrect timezone offset. To correct this, you must use the normalize() method on the timezone object.

    Best Practice: The preferred way to handle time is to perform all calculations in UTC and only convert to local time when generating output for humans.

    from datetime import datetime, timedelta
    from pytz import timezone
    
    eastern = timezone('US/Eastern')
    # Assume loc_dt is a localized datetime near a DST transition
    loc_dt = eastern.localize(datetime(2002, 10, 27, 1, 0, 0)) 
    
    # Arithmetic might result in incorrect offset
    before = loc_dt - timedelta(minutes=10)
    
    # Use normalize() to fix the offset
    correct_dt = eastern.normalize(before)
  5. Install pytz via pip or setup.py

    master

    You can install pytz using pip to get the latest version from PyPI, or by installing from a tarball using distutils.

    # Using pip
    pip install pytz
    
    # From a tarball (as administrative user)
    python setup.py install
  6. Set up a Dev Container for pytz development

    master

    To prepare a development environment (such as a Dev Container) for pytz, you must install a wide range of legacy and modern Python versions, build essentials, and packaging tools. This involves generating locales, adding the deadsnakes PPA for various Python versions, and using ez_setup.py to bootstrap setuptools for older Python versions.

    # 1. Prepare system and add Python PPA
    locale-gen
    add-apt-repository ppa:deadsnakes/ppa
    apt update
    
    # 2. Install build tools and Python versions
    apt install tox bzr build-essential twine python-all python-all-dev python3-all python3-all-dev python3-docutils python3-sphinx python3-flake8 python-flake8 python2.4-complete python2.5-complete python2.6-complete python3.1-complete python3.2-complete python3.3-complete python3.4-complete python3.5 python3.5-dev python3.7 python3.7-dev  python-wheel python3-wheel python-pip python3-pip
    
    # 3. Bootstrap setuptools for legacy Python versions
    wget https://raw.githubusercontent.com/pypa/setuptools/bootstrap-py24/ez_setup.py -O - | python2.4
    wget https://raw.githubusercontent.com/pypa/setuptools/bootstrap-py24/ez_setup.py -O - | python2.5
    wget https://bootstrap.pypa.io/ez_setup.py -O - | python2.6
    wget https://bootstrap.pypa.io/ez_setup.py -O - | python3.1
    wget https://bootstrap.pypa.io/ez_setup.py -O - | python3.2
    wget https://bootstrap.pypa.io/ez_setup.py -O - | python3.3
    wget https://bootstrap.pypa.io/ez_setup.py -O - | python3.4
  7. Convert between timezones using astimezone()

    master

    To convert an existing localized datetime from one timezone to another, use the standard Python astimezone() method. This is the recommended way to move between timezones.

    from datetime import datetime
    from pytz import timezone, utc
    
    # Start with a UTC datetime
    utc_dt = datetime(2006, 3, 26, 21, 34, 59, tzinfo=utc)
    
    # Convert to Australia/Sydney
    au_tz = timezone('Australia/Sydney')
    au_dt = utc_dt.astimezone(au_tz)
    
    print(au_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
    # Output: 2006-03-27 08:34:59 AEDT+1100
  8. How to localize naive datetimes with localize()

    master

    To create a localized datetime from a naive datetime (one without timezone information), use the localize() method provided by the timezone object.

    Warning: Do not pass a pytz timezone object directly into the tzinfo argument of the standard datetime constructor (e.g., datetime(..., tzinfo=timezone('US/Eastern'))). This will result in incorrect behavior for many timezones. Instead, create a naive datetime and then call localize() on the timezone instance.

    from datetime import datetime
    from pytz import timezone
    
    eastern = timezone('US/Eastern')
    naive_dt = datetime(2002, 10, 27, 6, 0, 0)
    
    # Correct way
    loc_dt = eastern.localize(naive_dt)
    print(loc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))
    # Output: 2002-10-27 06:00:00 EST-0500
  9. Migration guidance for Python 3.9+

    master
    The pytz project is currently in maintenance mode. If your project uses Python 3.9 or later, it is recommended to migrate to the timezone functionality built into the Python core library. For data support, you should use the tzdata package instead of pytz.
  10. Handle ambiguous or non-existent times with normalize()

    master

    When performing arithmetic on localized datetimes (like adding or subtracting time), the timezone offset might change (e.g., crossing a Daylight Savings Time boundary). Use the normalize() method on the timezone object to correct the offset and ensure the datetime is valid for that zone.

    from datetime import datetime, timedelta
    import pytz
    
    eastern = pytz.timezone('US/Eastern')
    # Create a localized datetime
    loc_dt = eastern.localize(datetime(2002, 10, 27, 1, 0, 0))
    
    # Subtracting time might cross a DST boundary
    new_dt = loc_dt - timedelta(minutes=10)
    
    # Correct the timezone information
    normalized_dt = eastern.normalize(new_dt)
  11. Install the tz distribution

    master

    To install the Time Zone Database (tz, tzdb, or zoneinfo), you must first acquire the code and data from the IANA repository. After acquisition, you may need to modify the Makefile to suit your specific platform (especially if not using GNU/Linux).

    Install the distribution by running make with the TOPDIR variable set to your desired installation directory.

    make TOPDIR="$HOME/tzdir" install
  12. Access timezones by country code

    master

    You can retrieve a list of timezones used in a specific country using the pytz.country_timezones() function, which accepts an ISO 3166 two-letter country code. Additionally, pytz.country_names provides a mapping from ISO 3166 codes to English country names.

    import pytz
    
    # Get timezones for New Zealand
    print(' '.join(pytz.country_timezones['nz']))
    
    # Get country name from code
    print(pytz.country_names['nz'])
    
    # Using the function with a code
    print(' '.join(pytz.country_timezones('ch')))