Python Timezone Handling with pytz | Generated by AI

Home 2025.10

Installing pytz

pytz is a third-party Python library for handling timezone-aware datetime objects. Note that as of Python 3.9+, the built-in zoneinfo module is preferred for new code (it’s in the standard library and handles updates automatically), but pytz remains widely used.

To install pytz, use pip:

pip install pytz

Basic Usage with pytz

pytz works with Python’s datetime module. Key concepts:

Import required modules:

import datetime
import pytz

Examples

1. Get Current Time in a Specific Timezone

Use pytz.utc or specific timezones. Always work with UTC internally for best practices.

# Get current UTC time
utc_now = datetime.datetime.now(pytz.utc)
print(utc_now)  # e.g., 2023-10-15 14:30:00+00:00

# Get current time in US Eastern time
eastern = pytz.timezone('US/Eastern')
eastern_now = datetime.datetime.now(eastern)
print(eastern_now)  # e.g., 2023-10-15 10:30:00-04:00 (adjusts for DST)

2. Localizing a Naive Datetime

Convert a naive (timezone-unaware) datetime to a timezone-aware one.

# Create a naive datetime (e.g., October 15, 2023, 12:00)
naive_dt = datetime.datetime(2023, 10, 15, 12, 0)
print(naive_dt)  # 2023-10-15 12:00:00

# Localize to US Eastern time
eastern = pytz.timezone('US/Eastern')
aware_dt = eastern.localize(naive_dt)
print(aware_dt)  # 2023-10-15 12:00:00-04:00

3. Converting Between Timezones

First localize a datetime, then convert.

# Start with UTC time
utc_dt = pytz.utc.localize(datetime.datetime(2023, 10, 15, 14, 0))
print(utc_dt)  # 2023-10-15 14:00:00+00:00

# Convert to Pacific time
pacific = pytz.timezone('US/Pacific')
pacific_dt = utc_dt.astimezone(pacific)
print(pacific_dt)  # 2023-10-15 07:00:00-07:00

4. Handling Lists of Timezones

pytz supports common timezone names from the Olson database.

# List available timezones
print(pytz.all_timezones[:10])  # Sample: ['Africa/Abidjan', 'Africa/Accra', ...]

# Or country-specific
print(pytz.country_timezones['US'])  # ['America/New_York', 'America/Los_Angeles', ...]

For newer Python versions, use the built-in zoneinfo instead of pytz for simplicity:

from zoneinfo import ZoneInfo
import datetime

# Equivalent to pytz examples
eastern_now = datetime.datetime.now(ZoneInfo('US/Eastern'))
aware_dt = datetime.datetime(2023, 10, 15, 12, 0).replace(tzinfo=ZoneInfo('US/Eastern'))

Common Issues and Tips


Back

x-ai/grok-code-fast-1

Donate