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 datetime import pytz # get the standard UTC time UTC = pytz.utc # it will get the time zone # of the specified location IST = pytz.timezone( 'Asia/Kolkata' ) # print the date and time in # standard format print ( "UTC in Default Format : " , datetime.now(UTC)) print ( "IST in Default Format : " , datetime.now(IST)) # print the date and time in # specified format datetime_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 datetime import pytz # get the standard UTC time original = pytz.timezone( 'Asia/Kolkata' ) # it will get the time zone # of the specified location converted = pytz.timezone( 'US/Eastern' ) # print the date and time in # specified format dateTimeObj = datetime.now(original) print ( "Original Date & Time: " , dateTimeObj.strftime( '%Y:%m:%d %H:%M:%S %Z %z' )) # converted dateTimeObj = 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 datetime import pytz # get the standard UTC time original = pytz.utc # create datetime object dateTimeObj = 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 location for 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: