What is the difference between naive and aware?
The datetime class
The datetime class initiates the datetime objects that contain information about the date, time, and time zone.
class datetime.datetime(year, month, day, hour, minute,
second, microsecond, tzinfo, fold)
Note: The first three arguments,
year,month, anddayarguments are mandatory, while all the other arguments are optional.
# import datetime class from datetime modulefrom datetime import datetime# Initializing with year, month and datedate_obj = datetime(1998, 12, 27)print("Date: ", date_obj)# Initializing with timedatetime_obj = datetime(1998, 12, 27, 13, 22, 2, 398740)print("Date with Time: ",datetime_obj)# to get current datetime use now()current_time = datetime.now()# Print Current timeprint("Current Time: " ,current_time)
Types of datetime class
The datetime class is classified into two categories:
- Naive
- Aware
If a datetime object has time zone information, then it will be aware. Otherwise, it will be naive.
In the case of a naive datetime object, tzinfo will be None and time will be in UTC(+00:00).
Example
# import date time classfrom datetime import datetime# import pytz for timezoneimport pytz# Naive timeN = datetime.now()print("----Naive----")print("UTC time:", N)# time zone of Karachitz_Karachi = pytz.timezone('Asia/Karachi')datetime_Karachi = datetime.now(tz_Karachi)print("----Aware----")print("Karachi time:", datetime_Karachi)# time zone of NewYorktz_NewYork = pytz.timezone('America/New_York')datetime_NewYork= datetime.now(tz_NewYork)print("NewYork time:", datetime_NewYork)
Explanation
In line 7, datetime.now() does not have any time zone information. It just returns the current system time in UTC (+00:00).
To display time according to the right timezone, the pytz module must be used.
To use the pytz module, “Asia/Karachi” and “America/New_York” in line 12 and 17, respectively, are taken as arguments of the pythz.timezone() function. This function is then called as an argument inside datetime.now().
Hence, lines 13 and 18 return the local time with respect to the local timezone.
Free Resources