In this article, we will discuss how to convert date and time with different timezones in Python. To do this we will use one of the modules of python pytz . This module brings the Olson tz database into Python and this library allows accurate and cross-platform timezone calculations using Python. The method pytz.timezone() generates the current timezone of a particular region.
Syntax:
pytz.timezone(“name of the time zone”)
Ex: pytz.timezone(“Asia/Kolkata”)
Example 1:
In the below program the current UTC time is converted according to Asia/Kolkata timezone.
Python3
from datetime import datetimeimport pytz # get the standard UTC timeUTC = pytz.utc # it will get the time zone# of the specified locationIST = pytz.timezone('Asia/Kolkata') # print the date and time in# standard formatprint("UTC in Default Format : ", datetime.now(UTC)) print("IST in Default Format : ", datetime.now(IST)) # print the date and time in# specified formatdatetime_utc = datetime.now(UTC)print("Date & Time in UTC : ", datetime_utc.strftime('%Y:%m:%d %H:%M:%S %Z %z')) datetime_ist = datetime.now(IST)print("Date & Time in IST : ", datetime_ist.strftime('%Y:%m:%d %H:%M:%S %Z %z')) |
Output:

Example 2:
Here is another program where the current Asia/Kolkata timezone is converted to US/Eastern timezone.
Python3
from datetime import datetimeimport pytz # get the standard UTC timeoriginal = pytz.timezone('Asia/Kolkata') # it will get the time zone# of the specified locationconverted = pytz.timezone('US/Eastern') # print the date and time in# specified formatdateTimeObj = datetime.now(original)print("Original Date & Time: ", dateTimeObj.strftime('%Y:%m:%d %H:%M:%S %Z %z')) # converteddateTimeObj = datetime.now(converted )print("Converted Date & Time: ", dateTimeObj.strftime('%Y:%m:%d %H:%M:%S %Z %z')) |
Output:

One can get all timezone values present in the pytz by executing the below code:
for timezone in pytz.all_timezones:
print(timezone) Below is a program to convert a particular timezone to multiple timezones of the Indian region:
Python3
from datetime import datetimeimport pytz # get the standard UTC timeoriginal = pytz.utc # create datetime objectdateTimeObj = datetime.now(original)print("Original Date & Time: ", dateTimeObj.strftime('%Y:%m:%d %H:%M:%S %Z %z')) # it will get the time zone# of the specified locationfor timeZone in pytz.all_timezones: if 'Indian/' in timeZone: dateTimeObj = datetime.now(pytz.timezone(timeZone)) print(timeZone,":",dateTimeObj.strftime('%Y:%m:%d %H:%M:%S %Z %z')) |
Output:

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


