Set timezone via pytz module

import pytz
import datetime

amsterdam = pytz.timezone("Europe/Amsterdam")
iran = pytz.timezone("Iran")
tokyo = pytz.timezone("Asia/Tokyo")

print(datetime.datetime.now(tz=amsterdam))
print(datetime.datetime.now(tz=iran))
print(datetime.datetime.now(tz=tokyo))

# prints all availablle timezones
for timeZone in pytz.all_timezones:
    print(timeZone)
Code Explanation

This Python script demonstrates how to retrieve and print the current datetime in different time zones using the pytz and datetime modules. Additionally, it lists all available time zones provided by pytz.

Importing Modules
  • pytz: This module provides timezone definitions for handling timezone calculations more accurately than the standard datetime module alone.
  • datetime: This module is used to manipulate dates and times in Python. It’s enhanced by pytz for timezone-aware datetime operations.
Defining Timezones
  • amsterdam: A timezone object for Amsterdam is created using pytz.timezone("Europe/Amsterdam"). This object represents the timezone for Amsterdam.
  • iran: Similarly, a timezone object for Iran is created using pytz.timezone("Iran"), representing Iran’s official timezone.
  • tokyo: A timezone object for Tokyo is created with pytz.timezone("Asia/Tokyo"), which is the timezone definition for Tokyo.
Printing the Current Datetime in Different Timezones
  • Each print statement outputs the current datetime in the respective timezones of Amsterdam, Iran, and Tokyo. The datetime.datetime.now(tz=timezone) function is used, where tz is specified as one of the timezone objects defined earlier. This function returns the current date and time adjusted to the specified timezone. This allows for the accurate representation of the local current time in different regions around the world.
Listing All Available Timezones
  • The script iterates over pytz.all_timezones, which is a list containing the names of all timezones recognized by the pytz library. Each timezone name is printed out in a loop. This part of the script is particularly useful for developers needing to know the exact string identifiers for various timezones, which are necessary for creating timezone-aware datetime objects.

This functionality is essential in global applications where operations are dependent on local times in various parts of the world. For example, in scheduling applications, logging systems, or any software that needs to handle date and time information across multiple regions accurately.

Output
2022-12-10 20:08:38.663648+01:00
2022-12-10 22:38:38.663764+03:30
2022-12-11 04:08:38.663788+09:00
Africa/Abidjan
Africa/Accra
...
Etc/GMT+6
Etc/GMT-2
Etc/GMT-3
Etc/GMT-4
Etc/GMT-5
Etc/GMT-6
Etc/GMT-7
...
Europe/Amsterdam
Europe/Andorra
Europe/Astrakhan
Europe/Athens
Europe/Belfast
Indian/Antananarivo
Indian/Chagos
Indian/Christmas
...
Pacific/Wake
Pacific/Wallis
Pacific/Yap
Poland
Portugal
...