Checking if an object is timezone aware or not
We can easily check if a datetime object is timezone-aware or not. For this, we will store the current date and time in a new variable using the datetime.now() function of datetime module.
Syntax: datetime.now(tz)
Parameters: tz : Specified time zone of which current time and date is required. (Uses Greenwich Meridian time by default.)
Then we will check the timezone information of the object stored in the tzinfo base class. tzinfo is an abstract base class for time zone information objects.
Python3
# Importing the datetime module import datetime # Storing the current date and time in # a new variable using the datetime.now() # function of datetime module current_date = datetime.datetime.now() # 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" ) |
Output:
Unaware
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.