How to do time zone conversion with Python?

Sometimes, we want to do time zone conversion with Python.

In this article, we’ll look at how to do time zone conversion with Python.

How to do time zone conversion with Python?

To do time zone conversion with Python, we can use the pytz module.

For instance, we write:

from datetime import datetime
from pytz import timezone

fmt = "%Y-%m-%d %H:%M:%S %Z%z"
timezonelist = ['UTC', 'US/Pacific', 'Europe/Berlin']
for zone in timezonelist:
    now_time = datetime.now(timezone(zone))
    print(now_time.strftime(fmt))

We loop through timezonelist to print the current date and time in different time zones.

In the loop, we get the current date and time in the given zone with:

datetime.now(timezone(zone))

Then we call strftime with the fmt format string to return the date and time string from the date time object.

%Y is the year.

%m is the month.

%d is the day.

%H is the hour.

%M is the minute.

And %S is the seconds.

As a result, we get something like:

2021-10-31 20:19:08 UTC+0000
2021-10-31 13:19:08 PDT-0700
2021-10-31 21:19:08 CET+0100

printed.

Conclusion

To do time zone conversion with Python, we can use the pytz module.