Python pytz Module: Mastering Timezones in Python 

Python Pytz Module Mastering Timezones In Python 

Python offers many useful libraries and modules to simplify coding. One such module that stands out for handling date and time data is pytz. It accounts for daylight saving time, enabling precise date-time conversions. As developers, it saves us the trouble of manual time calculations. It also supports a wide range of timezones, making it ideal for applications with a diverse user base.

This module is particularly useful when working with databases stored in Coordinated Universal Time (UTC) but requiring conversions to local times for display. Understanding how to effectively use pytz can greatly enhance your Python applications, especially those dealing with time-sensitive data.

The pytz module’s versatility and functionality allow it to shine in enabling accurate timezone handling in Python software. By simplifying timezone management for developers and providing local time data for international users, pytz makes a valuable addition to any Python developer’s toolkit

Also read: Python time module

How to Install the Python pytz Module for Better Date-Time Handling

The Python pytz module offers a comprehensive set of functions and variables to handle date-time conversions across various timezones. The module provides a list or set of all supported timezones, commonly used timezones, country names, and country timezones. The pytz.timezone() function can fetch the current time of a specified timezone.

By running the ‘pip install pytz’ command, you can easily install the pytz module in your Python environment.

pip install pytz
Pytz Installation 1
Verifying Your Installation of the pytz Module

Dive into the Core Functions and Variables of the Python pytz Module

Let’s now go ahead and explore the different methods and variables of the pytz module.


1. Exploring Global Timezones with all_timezones and all_timezones_set

The all_timezones function of the pytz module returns a list of all the time-zones supported by Python’s pytz module.

Example:

import pytz

print('The timezones supported by pytz module: ', pytz.all_timezones, '\n')

Output Snippet:

The timezones supported by pytz module:  ['Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers', 'Africa/Asmara', 'Africa/Asmera', 'Africa/Bamako', 'Africa/Bangui', 'Africa/Banjul']

We have shown only a few values because the actual list is very long.


This variable returns a set of all the supported timezones.

Example:

import pytz
print('List of supported timezones by pytz module: ', pytz.all_timezones_set, '\n')

Output Snippet:

List of supported timezones by pytz module:  LazySet({'America/Port-au-Prince', 'Asia/Ust-Nera', 'Asia/Vientiane', 'Australia/Hobart', 'Asia/Ulaanbaatar', 'Africa/Lome'})

Also read: Difference between two dates in Python

2. Common Timezones Using common_timezones and common_timezones_set

This variable returns a list of commonly used time-zones.

Example:

import pytz

print('Commonly used time-zones: ', pytz.common_timezones, '\n')

Output Snippet:

Commonly used time-zones:  ['Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers', 'Africa/Asmara', 'Africa/Bamako', 'Africa/Bangui', 'Africa/Banjul', 'US/Pacific', 'UTC']

import pytz
print('common_timezones_set() = ', pytz.common_timezones_set, '\n')

Output:

common_timezones_set() =  LazySet({'America/Eirunepe', 'Africa/Kinshasa', 'Australia/Sydney', 'Europe/Malta', 'America/Tortola', 'Canada/Pacific', 'America/Argentina/Cordoba'})

3. Understanding the Time in Different Zones Using pytz.timezone() in Python

The pytz.timezone() returns the timezone object by the name. And, the datetime.now() returns the date-time of that particular time-zone.

from datetime import datetime
import pytz
# getting utc timezone
utc_time = pytz.utc

# getting timezone by name
ist_time = pytz.timezone('Asia/Kolkata')

# getting datetime of specified timezone
print('Datetime of UTC Time-zone: ', datetime.now(tz=utc_time))
print('Datetime of IST Time-zone: ', datetime.now(tz=ist_time))

Output:

Datetime of UTC Time-zone:  2020-01-03 17:49:14.220167+00:00
Datetime of IST Time-zone:  2020-01-03 23:19:14.220167+05:30

4. Decode Country Names with Python’s pytz Module: country_names

The country_names returns a dictionary of country ISO Alpha-2 Code and country name as a key-value pair.

import pytz

print('country_names =')
for key, val in pytz.country_names.items():
    print(key, '=', val, end=',')
print('\n')
print('Country name equivalent to the input country code: ', pytz.country_names['AQ'])

Output:

country_names =
AD = Andorra,AE = United Arab Emirates,AF = Afghanistan,AG = Antigua & Barbuda,AI = Anguilla,AL = Albania,AM = Armenia,AO = Angola,AQ = Antarctica,ZW = Zimbabwe,
Country name equivalent to the input country code:  Antarctica

5. Using country_timezones to find time data from across different parts fo the world

This function provides a dictionary of country ISO Alpha-2 Code as key and list of supported time-zones for a particular input key (country code) as output.

import pytz
print('country_timezones =')
for key, val in pytz.country_timezones.items():
    print(key, '=', val, end=',')
print('\n')
print('Time-zones supported by Antartica =', pytz.country_timezones['AQ'])

Output:

country_timezones =
AD = ['Europe/Andorra'],AE = ['Asia/Dubai'],AF = ['Asia/Kabul'],AG = ['America/Antigua'],AI = ['America/Anguilla'],AL = ['Europe/Tirane'],AM = ['Asia/Yerevan'],AO = ['Africa/Luanda'],ZW = ['Africa/Harare'],
Time-zones supported by Antartica = ['Antarctica/McMurdo', 'Antarctica/Casey', 'Antarctica/Davis', 'Antarctica/DumontDUrville', 'Antarctica/Mawson', 'Antarctica/Palmer']

Conclusion

The Python pytz module is an incredibly powerful tool when dealing with date and time across different timezones. With it, managing time in your Python applications becomes a breeze. After all, in the digital age, isn’t time one of our most precious resources?

References