Timezone aware object using pytz
You can also use the pytz module to create timezone-aware objects.
For this, we will store the current date and time in a new variable using the datetime.now() function of datetime module and then we will add the timezone using timezone function of pytz module.
Python3
# Importing the datetime module import datetime import pytz # Storing the current date and time in # a new variable using the datetime.now() # function of datetime module and adding the timezone # using timezone function of pytz module. current_date = datetime.datetime.now(pytz.timezone( 'Africa/Abidjan' )) # Printing the value of current_date print (current_date) |
Output:
2021-08-30 04:35:37.036990+00:00
Now let’s check if the object is timezone aware or not using the method we used in the 1st section of the article.
Python3
# Importing the datetime module import datetime import pytz # Storing the current date and time in # a new variable using the datetime.now() # function of datetime module and adding the timezone # using timezone function of pytz module. current_date = datetime.datetime.now(pytz.timezone( 'Africa/Abidjan' )) # Checking the timezone information of the # object stored in tzinfo base class if current_date.tzinfo = = None or current_date.\ tzinfo.utcoffset(current_date) = = None : # If passes the above condition then # the object is unaware print ( "Unaware" ) else : # Else printing "Aware" print ( "Aware" ) # Printing the value of current_date print (current_date) |
Output:
Aware 2021-08-30 04:46:40.670455+00:00
How to make a timezone aware datetime object in Python
In this example, we are going to see how to make a timezone-aware DateTime object in Python.
Timezone-aware objects are Python DateTime or time objects that include timezone information. An aware object represents a specific moment in time that is not open to interpretation.