CodeGym /Courses /Python SELF EN /Introduction to Working with Time Zones

Introduction to Working with Time Zones

Python SELF EN
Level 40, Lesson 2
Available

1. Why Time Zones Are Important

Time zones aren’t just a convenient excuse for a little jet lag on international flights. They play a critical role in programming, especially when dealing with global applications and services. Keeping track of time across time zones is key for storing and displaying data, scheduling tasks, coordinating teams around the world, and much more. If you ignore time zones, your code could turn into a real-time anomaly, and no one wants that, right?

What Are Time Zones?

A time zone is a region where all clocks show the same standard time. Each time zone is defined by its offset from Coordinated Universal Time (UTC). For example, if your zone's time is two hours ahead of UTC, your time zone is labeled as UTC+2.

Converting Time Between Zones

When working with time-stamped data, you often need to adapt the time from one zone to another. For example, you’ve scheduled a marketing campaign launch on a server running on UTC, but you want it to go live at exactly 9 AM New York time (UTC-5). This is where time zones come into play.

To make this easier, Python provides the pytz library, which helps with time zone conversions. Let’s take a look at some examples of its usage.

2. Working with Time Zones in Python

Using pytz to Handle Time Zones

Once installed, you can start experimenting with pytz. Let’s import it along with datetime:

Python

from datetime import datetime
import pytz

Getting the Current Time in a Specific Time Zone

Let’s find out the current time in New York:

Python

# Create a time zone object for New York
ny_tz = pytz.timezone('America/New_York')

# Get the current time in UTC
utc_now = datetime.now(pytz.utc)

# Convert UTC time to New York time
ny_time = utc_now.astimezone(ny_tz)

# Print the result
print("Current time in New York:", ny_time)

This code converts the current UTC time to New York time, which is then printed in a readable format.

Converting Time Between Zones

Let’s say you have a date for an important event in London, and you need to find out when it will happen in Tokyo time.

Python

# Event time in London
event_time = datetime(2023, 10, 31, 15, 0, 0, tzinfo=pytz.utc).astimezone(pytz.timezone('Europe/London'))

# Convert time to Tokyo
tokyo_tz = pytz.timezone('Asia/Tokyo')
event_time_tokyo = event_time.astimezone(tokyo_tz)

print("Event time in Tokyo:", event_time_tokyo)

3. Advanced Work with Time Zones in Python

Listing Available Time Zones

You can get a list of all time zones supported by the pytz library using pytz.all_timezones.

Python

import pytz

print("Example time zones:")
for timezone in pytz.all_timezones[:5]:  # Show the first 5 time zones
    print(timezone)

Output (partial):

Example time zones:
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara

Setting a Time Zone and Creating a `datetime` Object

Using pytz.timezone(), you can set a specific time zone for a date and time. Let’s see how to create a datetime object with a defined time zone.

Python

from datetime import datetime
import pytz

# Select the time zone "Europe/Moscow"
moscow_timezone = pytz.timezone("Europe/Moscow")
current_time_moscow = datetime.now(moscow_timezone)
print("Current time in Moscow:", current_time_moscow)

Handling Daylight Saving Time (DST)

One of the important aspects of time zones is handling daylight saving time, which pytz automates. For example, if you’re working with US time, the library will automatically apply the daylight saving time shift when it’s active.

Python

from datetime import datetime
import pytz

# Set a date during daylight saving time
date_in_summer = datetime(2024, 7, 1, 12, 0, 0)
ny_timezone = pytz.timezone("America/New_York")
ny_summer_time = ny_timezone.localize(date_in_summer)
print("Summer time in New York:", ny_summer_time)

# Set a date outside of daylight saving time
date_in_winter = datetime(2024, 12, 1, 12, 0, 0)
ny_winter_time = ny_timezone.localize(date_in_winter)
print("Winter time in New York:", ny_winter_time)

Here, pytz automatically detects that July 1st is during daylight saving time and applies the one-hour shift.

Useful Functions for Working with Time Zones

  • Getting All Time Zones: pytz.all_timezones returns a list of all time zones.
  • Converting to UTC: The astimezone(pytz.utc) method converts any time to UTC.
  • Converting String Time to datetime: Use datetime.strptime() to convert string time to datetime and add a time zone.
  • Updating Time Zones: Use pytz.update() to update time zones.
1
Task
Python SELF EN, level 40, lesson 2
Locked
Getting the current time in different time zones
Getting the current time in different time zones
2
Task
Python SELF EN, level 40, lesson 2
Locked
Time Conversion Between Time Zones
Time Conversion Between Time Zones
3
Task
Python SELF EN, level 40, lesson 2
Locked
Event Planning Across Different Time Zones
Event Planning Across Different Time Zones
4
Task
Python SELF EN, level 40, lesson 2
Locked
Working with Daylight Saving and Standard Time
Working with Daylight Saving and Standard Time
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION