Computer >> Computer tutorials >  >> Programming >> Python

How to convert date and time with different timezones in Python?


The easiest way in Python date and time to handle timezones is to use the pytz module. This library allows accurate and cross platform timezone calculations. pytz brings the Olson tz database into Python. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference (datetime.tzinfo).

Before you use it you'll need to install it using −

$ pip install pytz

Example

You can use the pytz library as follows −

from datetime import datetime
from pytz import timezone
format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(format))
# Convert to Asia/Kolkata time zone
now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
print(now_asia.strftime(format))

Output

This will give the output −

2018-01-03 07:05:50 UTC+0000
2018-01-03 12:35:50 IST+0530