Python

How to use the PYTZ module of Python

Date and time values vary based on the zone. These values are needed to change for those Python applications that require dealing with international users. According to the zone, the dateTime module of Python cannot convert the date and time values. This problem can be solved by using the pytz module of Python. This module is not installed in Python. So, you have to install this module before using it in the script. How the pyzt module can be installed and used in Python, have shown in this tutorial.

Install PYZT module:

Run the following command to install the pyzt module before practicing the examples of this tutorial.

$ pip install pytz

Example-1: Print all supported and commonly used time zones

The following script will print all supported time zones and the widely used time zones using the pyzy module. The pyzt module is imported at the beginning of the script. pytz.all_timezones attribute returns the list of all supported time zones as a list object. pytz.common_timezones attribute returns the list of all commonly used time zones as a list object. Two lists will be printed after executing this script.

# Import pytz module
import pytz

# Print all supported timezones
print('The timezones supported by pytz module:\n', pytz.all_timezones, '\n')
# Print commonly used time-zones
print('Commonly used time-zones:\n', pytz.common_timezones, '\n')

Output:

The following output will appear after executing the above script.

Example-2: Print country names

The following script will print the list of country names with country codes and the country’s name of a particular country code. pytz.country_names.items() method returns a dictionary object of country names with the country code. The country codes are assigned in the dictionary object’s keys, and the country names are assigned in the dictionary object’s values. The for loop has used in the script to print the country names with the country code in each line by iterating the dictionary object returned by pytz.country_names.items(). Next, the country name of the ā€˜JPā€™ country code will be printed.

# Import pytz module
import pytz
'''
Print the country name with country code in each line
using for loop
'''

print('country_names:')
for key, val in pytz.country_names.items():
    print(val, '(', key, ')')

# Print the country name of the particular country code
print('\nCountry name based on country code(JP):', pytz.country_names['JP'])

Output:

The following output will appear after executing the above script. The output shows the country names and country codes in the brackets. The country name of ā€˜JPā€™ is Japan that is printed later.

Example-3: Print date and time based on time zone

The date and time values vary based on the time zone. The following script will print the date and time of the current time zone at first. Next, the time zone will be changed to US/Eastern by using pytz.timezone() method and the date and time will be printed based on the US/Eastern time zone. Next, the time zone will be changed to Asia/Hong_Kong time zone, and the date and time will be printed based on Asia/Hong_Kong time zone. The date and time of the UTC and IST time zones will be printed later.

# Import datetime module
import datetime as dt
# Import pyzt module
import pytz

# Retrieve the current date
source_date = dt.datetime.now()
# Print the current data and time
print('The current date and time:\n', source_date)

# Set the timezone to US/Eastern
currentTimeZone = pytz.timezone('US/Eastern')
# Print the current time-zone Asia/Hong_Kong
print('\nThe time-zone is set to:\n', currentTimeZone)
# Read and print the current date and time of the time-zone
currentDateWithTimeZone = currentTimeZone.localize(source_date)
print('The date and time of this time-zone:\n', currentDateWithTimeZone)

# Set the target time-zone
newTimeZone = pytz.timezone('Asia/Hong_Kong')
print('\nThe time-zone is set to:\n', newTimeZone)
# Read and print the current date and time of the newly defined time-zone
newDateWithTimezone = currentDateWithTimeZone.astimezone(newTimeZone)
print('The date and time of this time-zone:\n', newDateWithTimezone)


# Read the datetime of the specified timezone
print('\nDatetime of UTC Time-zone: ', dt.datetime.now(tz=currentTimeZone))
print('Datetime of IST Time-zone: ', dt.datetime.now(tz=newTimeZone))

Output:

The following output will appear after executing the above script. The output shows that the date and time values vary based on the time zone.

Example-4: Print the formatted date and time

In the previous examples, the date and time values are printed in the default format. The following script will print the formatted data and time based on the selected time zone. The format of the date and time has defined at the beginning of the script. According to the format, the date will print in dd-mm-yyyy format, and the time will print in hh:mm:ss format. Next, the time zone will be assigned to America/Toronto, and the date and time will be printed by using the strftime() function with the format mentioned above. Next, the time zone will be assigned to Asia/Dhaka and printed like before.

# Import DateTime module
from datetime import datetime
# Import timezone module
from pytz import timezone

# Set the date and time format
dt_format = "%d-%m-%Y %H:%M:%S"

# Set the current time to America/Toronto zone
torontoZone = datetime.now(timezone('America/Toronto'))
print('Date and time of toronto zone:\n', torontoZone.strftime(dt_format))

# Change the timezone to Asia/Dhaka
dhakaZone = torontoZone.astimezone(timezone('Asia/Dhaka'))
print('Date and time of dhaka zone:\n', dhakaZone.strftime(dt_format))

Output:

The following output will appear after executing the above script. The output shows that the time difference between Toronto and Dhaka is 10 hours.

Conclusion:

The pyzt module has many built-in functions to work with the different time zones’ date and time values. The website’s date and time values can be changed according to the visitor’s time zone by using this module. This module’s primary uses have been explained in this tutorial by using different examples to help the readers understand this module’s purpose.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.