Print time in all time zones in Python
In this tutorial, we are going to see how we can print time in all time zones in Python. We will also see a few real-time examples.
Using the pytz library to print time in all time zones
The pytz library in Python can handle problems related to time zones with relative ease and efficiency. Hence, it is most commonly used to get time in different time zones. The reason for it being used so frequently is that it brings the Olson tz database into Python. In addition to pytz library, we are going to use datetime and tzlocal libraries.
Let us import these
from datetime import datetime from pytz import timezone from tzlocal import get_localzone
So, we can see that from the library tzlocal, we will get local timezone. But, let us see how to get the time for a particular time zone.
# Current time in Kolkata now_kol = datetime.now(timezone('Asia/Kolkata')) print(now_kol.strftime(format)) format = "%Y-%m-%d %H:%M:%S %Z%z"
2020-03-17 15:41:58 IST+0530
Here, we can see that to find the current time in any time zone present it the pytz library, the function datetime.now() is called. Also, the function strftime() returns the date and time in the string format we have provided above.
Let us see some more examples.
# Current time in UTC now_utc = datetime.now(timezone('US/Eastern')) print(now_utc.strftime(format)) # Current time in London now_lon = datetime.now(timezone('Europe/London')) print(now_lon.strftime(format)) # Current time in Sydney now_syd = datetime.now(timezone('Australia/Sydney')) print(now_syd.strftime(format))
2020-03-17 06:26:12 EDT-0400 2020-03-17 10:26:12 GMT+0000 2020-03-17 21:26:12 AEDT+1100
Hence, we have calculated the time for different time zones i.e US, Europe, Australia.