How to change timezone in Python

Sometimes the product or infrastructure engineers have to work on infrastructures that are spread out throughout the world. They have to work with machines that are in the US, Asia, Europe, and the UK, etc. So, time zones are all the more important for Python.

With the continuous advancement in today’s programming languages, there are plenty of modules maintained in almost all programming languages. In python, we have a time zone module called pytz, that allows for real-time cross-platform time zone calculations.

Getting current date and time in a specific format

To begin with, we will import the timezone library from the pytz module.

To install this module you can use this pip command.

pip install pytz

Or for Linux:

$ sudo pip install pytz

We will also need to import datetime from the datetime module. For the purpose of uniformity, we can specify the format in which we want our output of the date and time to be. In this program, we will specify it to be in YY-MM-DD HH:MM:SS format.

On the datetime library, we will call the now() method to get the current time in the specified format as and when the code is run. However, the output timezone format will be in its datetime object format. So, to change it to a more readable format, we convert it to string time format by calling strftime() method on it.

from pytz import timezone
from datetime import datetime

time_format = '%Y-%m%d %H:%M:%S %Z%z'
default_now = datetime.now()
formatted_now = datetime.now().strftime(time_format)

print("Date Time in defaut format: ", default_now, '\n')
print("Date Time in string format: ", formatted_now)

Output:

Date Time in defaut format: 2021-11-19 04:37:14.537946 

Date Time in string format: 2021-1119 04:37:14

Converting current date and time to multiple timezones

Now, we will create a list of time zones, and loop through it to convert the current time to that time zone. We will put various time zones from the US, Europe, Asia, and the UTC which is the standard one.

timezones = ['US/Central', 'Europe/London', 
             'Asia/Kolkata', 'Australia/Melbourne', 'UTC']
for tz in timezones:
dateTime = datetime.now(timezone(tz)).strftime(time_format)
print(f"Date Time in {tz} is {dateTime}")

Output:

Date Time in US/Central is 2021-1118 17:23:51 CST-0600
Date Time in Europe/London is 2021-1118 23:23:51 GMT+0000
Date Time in Asia/Kolkata is 2021-1119 04:53:51 IST+0530
Date Time in Australia/Melbourne is 2021-1119 10:23:51 AEDT+1100
Date Time in UTC is 2021-1118 23:23:51 UTC+0000

After that we will loop through all the timezones in the list we created as the parameter of the now() method on the datetime library to get all the time zones and the current time in respective time zones. We will also convert it to string format for it to be more convenient to read.

Also Read: Remove seconds from the datetime in Python

Leave a Reply

Your email address will not be published. Required fields are marked *