Python pytz module allows us to create timezone aware datetime instances.
Python pytz
Python datetime now() function creates the naive datetime instance from the current local system time. However, this function also takes timezone as an argument that should be the implementation of abstract type tzinfo
.
Python pytz module provides implementations of tzinfo
class that can be used to create timezone aware datetime instances.
Python pytz module can be installed using PIP command.
pip install pytz
Python pytz attributes
There are some attributes in pytz module to help us find the supported timezone strings. Let’s look at them.
all_timezones
Returns the list of all the supported timezones by the pytz module.
import pytz
print('all_timezones=", pytz.all_timezones, "n')
Output:
all_timezones = ['Africa/Abidjan', 'Africa/Accra', ... , 'UTC', 'Universal', 'W-SU', 'WET', 'Zulu']
The list is very long, the output is just showing some of the values.
all_timezones_set
Returns the set of all the supported timezones.
print('all_timezones_set=", pytz.all_timezones_set, "n')
Output:
all_timezones_set = LazySet({'America/St_Vincent', 'Asia/Thimphu', 'Etc/GMT+9', ... , 'Europe/Guernsey'})
Note that its a set, so the order of elements is not recorded and output in your system may be in different order.
common_timezones, common_timezones_set
Returns the list and set of commonly used timezones.
print('common_timezones=", pytz.common_timezones, "n')
print('common_timezones_set=", pytz.common_timezones_set, "n')
Output:
common_timezones = ['Africa/Abidjan', 'Africa/Accra', ... , 'US/Pacific', 'UTC']
common_timezones_set = LazySet({'America/St_Vincent', 'Asia/Thimphu', ... , 'Europe/Guernsey'})
country_names
Returns a dict of country ISO Alpha-2 Code as key and country full name as value.
print('country_names=")
for key, val in pytz.country_names.items():
print(key, "=', val, end=',')
print('n')
print('IN full name=", pytz.country_names["IN'])
Output:
country_names =
AD = Andorra,AE = United Arab Emirates, ... , ZW = Zimbabwe,
IN full name = India
country_timezones
Returns a dict of country ISO Alpha-2 Code as key and list of supported timezones as value.
print('country_timezones=")
for key, val in pytz.country_timezones.items():
print(key, "=', val, end=',')
print('n')
print('Supported timezones by US =', pytz.country_timezones['US'])
Output:
country_timezones =
AD = ['Europe/Andorra'],AE = ['Asia/Dubai'],...,ZW = ['Africa/Harare'],
Supported timezones by US = ['America/New_York', 'America/Detroit', 'America/Kentucky/Louisville', 'America/Kentucky/Monticello', 'America/Indiana/Indianapolis', 'America/Indiana/Vincennes', 'America/Indiana/Winamac', 'America/Indiana/Marengo', 'America/Indiana/Petersburg', 'America/Indiana/Vevay', 'America/Chicago', 'America/Indiana/Tell_City', 'America/Indiana/Knox', 'America/Menominee', 'America/North_Dakota/Center', 'America/North_Dakota/New_Salem', 'America/North_Dakota/Beulah', 'America/Denver', 'America/Boise', 'America/Phoenix', 'America/Los_Angeles', 'America/Anchorage', 'America/Juneau', 'America/Sitka', 'America/Metlakatla', 'America/Yakutat', 'America/Nome', 'America/Adak', 'Pacific/Honolulu']
Python pytz example
Let’s look at some examples of creating datetime instance with timezone information.
# getting utc timezone
utc = pytz.utc
# getting timezone by name
ist = pytz.timezone('Asia/Kolkata')
# getting datetime of specified timezone
print('UTC Time=", datetime.now(tz=utc))
print("IST Time=", datetime.now(tz=ist))
Output:
UTC Time = 2018-09-20 09:16:46.313898+00:00
IST Time = 2018-09-20 14:46:46.313951+05:30
localize()
We can create timezone aware datetime instance from given datetime instance using localize() function. Note that if you are creating current datetime instance then you should use it carefully, otherwise you will get the wrong information if there is a mismatch between local system timezone and pytz timezone provided.
# using localize() function, my system is on IST timezone
local_datetime = ist.localize(datetime.now())
print("IST Current Time=", local_datetime.strftime("%Y-%m-%d %H:%M:%S %Z%z'))
print('Wrong UTC Current Time=", utc.localize(datetime.now()).strftime("%Y-%m-%d %H:%M:%S %Z%z'))
Output:
IST Current Time = 2018-09-20 14:53:54 IST+0530
Wrong UTC Current Time = 2018-09-20 14:53:54 UTC+0000
Notice that I am using strftime() function to print timezone information when datetime is formatted to string.
Converting timezones
We can use astimezone()
function to get the time into a different timezone. Following code snippet will convert the earlier IST datetime instance to UTC time.
# converting IST to UTC
utc_datetime = local_datetime.astimezone(utc)
print('IST Current Time=", local_datetime.strftime("%Y-%m-%d %H:%M:%S %Z%z'))
print('UTC Time=", utc_datetime.strftime("%Y-%m-%d %H:%M:%S %Z%z'))
Output:
IST Current Time = 2018-09-20 14:56:03 IST+0530
UTC Time = 2018-09-20 09:26:03 UTC+0000
Reference: PYPI Docs