Converting Timezones
You can convert timezones using the in_timezone() method or using the timezone library directly. Refer following example for a better understanding
Note: UTC(Coordinated Universal Time) is the primary time standard by which the world regulates clocks and time.
Example :
Python3
# Importing library import pendulum # Getting current UTC time utc_time = pendulum.now( 'UTC' ) # Switching current timezone to # Kolkata timezone using in_timezone(). kolkata_time = utc_time.in_timezone( 'Asia/Kolkata' ) print ( 'Current Date Time in Kolkata =' , kolkata_time) # Generating Sydney timezone sydney_tz = pendulum.timezone( 'Australia/Sydney' ) # Switching current timezone to # Sydney timezone using convert(). sydney_time = sydney_tz.convert(utc_time) print ( 'Current Date Time in Sydney =' , sydney_time) |
Output :
Current Date Time in Kolkata = 2020-11-27T15:16:36.985136+05:30 Current Date Time in Sydney = 2020-11-27T20:46:36.985136+11:00
Python – Pendulum Module
The pendulum is one of the popular Python DateTime libraries to ease DateTime manipulation. It provides a cleaner and easier to use API. It simplifies the problem of complex date manipulations involving timezones which are not handled correctly in native datetime instances.
It inherits from the standard datetime library but provides better functionality. So you can introduce Pendulums Datetime instances in projects which are already using built-in datetime class (except for the libraries that check the type of the objects by using the type function like sqlite3).
To install this module run this command into your terminal:
pip install pendulum
Let’s see the simple examples:
You can create date-time instance using various methods like datetime(), local(),now(),from_format().
Example :
Python3
# import library import pendulum dt = pendulum.datetime( 2020 , 11 , 27 ) print (dt) #local() creates datetime instance with local timezone local = pendulum.local( 2020 , 11 , 27 ) print (local) print (local.timezone.name) |
Output:
2020-11-27T00:00:00+00:00 2020-11-27T00:00:00+05:30 Asia/Calcutta
Contact Us