Friday, December 27, 2024
Google search engine
HomeLanguagesPython pytz

Python pytz

Pytz brings the Olson tz database into Python and thus supports almost all time zones. This module serves the date-time conversion functionalities and helps user serving international client’s base. It enables time-zone calculations in our Python applications and also allows us to create timezone aware datetime instances. 

Installation

Python pytz module can be installed in the given way.

  • Using command line:
pip install pytz
  • Using tarball, run the following command as an administrative user:
python setup.py install
  • Using setuptools, the latest version will be downloaded for you from the Python package index:
easy_install --upgrade pytz

Converting timezones

By using astimezone() function we can convert the time into a different timezone.

Syntax: astimezone(t)

Parameter: t is time to be converted

Return: Converted timezone

Example: 

Python3




from datetime import datetime
from pytz import timezone
 
format = "%Y-%m-%d %H:%M:%S %Z%z"
 
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(format))
 
# Convert to Asia/Kolkata time zone
now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
print(now_asia.strftime(format))


Output

2020-12-30 04:38:16 UTC+0000
 

2020-12-30 10:08:16 IST+0530

Python pytz attributes 

There are some attributes in pytz module to help us find the supported timezone strings. These attributes will help understand this module better.

  • all_timezones

It returns the list all the available timezones with pytz.all_timezones:

Python3




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


Output:

The above output is showing some values, because the list is very large.

  •  all_timezones_set

It returns the set of all the available timezones with pytz.all_timezones_set:

Python3




import pytz
 
 
print('all the supported timezones set:',
      pytz.all_timezones_set, '\n')


Output

The output order will be different in your system because it is a set.

  • Common_timezones, Common_timezones_set 

It returns the list and set of commonly used timezones with pytz.common_timezones, pytz.common_timezones_set.

Python3




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


Output

  • country_names 

It returns a dict of country ISO Alpha-2 Code and country name as a key-value pair.

Python3




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


Output

country_names =AD = Andorra,AE = United Arab Emirates,TD = Chad,….,ZA = South Africa,ZM = Zambia,ZW = Zimbabwe,
equivalent country name to the input code:  India

  •  country_timezones

It returns a dictionary of country ISO Alpha-2 Code as key and list of supported time-zones for a particular input key (country code) as value

Python3




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


Output

country_timezones =
AD = [‘Europe/Andorra’],AE = [‘Asia/Dubai’],AF = [‘Asia/Kabul’],…..,ZM = [‘Africa/Lusaka’],ZW = [‘Africa/Harare’],
Time-zones supported by Antarctica = [‘Antarctica/McMurdo’, ‘Antarctica/Casey’, ‘Antarctica/Davis’, ‘Antarctica/DumontDUrville’, ‘Antarctica/Mawson’, ‘Antarctica/Palmer’, ‘Antarctica/Rothera’, ‘Antarctica/Syowa’, ‘Antarctica/Troll’, ‘Antarctica/Vostok’]

Python pytz example

Given below are certain examples to show how this module can be put to use.

Example 1: creating datetime instance with timezone information.

Python3




# import the modules
import pytz
import datetime
from datetime import datetime
 
 
# getting utc timezone
utc = pytz.utc
 
# getting timezone by name
kiev_tz = pytz.timezone('Europe/Kiev')
print('UTC Time =', datetime.now(tz=utc))
print('IST Time =', datetime.now(tz=kiev_tz))


Output

UTC Time = 2020-12-15 08:23:17.063960+00:00
 

IST Time = 2020-12-15 10:23:17.063988+02:00

Example 2: 

Python3




# import the modules
import pytz
import datetime
 
 
d = datetime.datetime(1984, 1, 10, 23, 30)
 
# strftime method allows you to print a string
# formatted using a series of formatting directives
d1 = d.strftime("%B %d, %Y")
 
# isoformat method used for quickly generating
# an ISO 8601 formatted date/time
d2 = d.isoformat()
print(d1)
print(d2)


Output

January 10, 1984
 

1984-01-10T23:30:00

localize()

localize() is the correct function to use for creating datetime aware objects with an initial fixed datetime value. The resulting datetime aware object will have the original datetime value. This function is provided by python library. pytz.localize() is useful for making a naive timezone aware. it is useful when a front-end client sends a datetime to the backend to be treated as a particular timezone (usually UTC).

Example :

Python3




import pytz
import datetime
from datetime import datetime
 
 
# using localize() function, my system is on IST timezone
ist = pytz.timezone('Asia/Kolkata')
utc = pytz.utc
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 = 2020-12-15 08:49:56 IST+0530
 

Wrong UTC Current Time = 2020-12-15 08:49:56 UTC+0000

Example

Python3




from datetime import datetime
from pytz import timezone
 
 
# Set the time to noon on 2019-08-19
naive = datetime(2019, 8, 19, 12, 0)
 
# Let's treat this time as being in the UTC timezone
aware = timezone('UTC').localize(naive)
print(aware)


Output

2019-08-19 12:00:00+00:00

RELATED ARTICLES

Most Popular

Recent Comments