Time is a substantial feature for many Data Science related tasks. For instance, daily sales and inventory information are of crucial importance for retail analytics. Algorithmic trading requires transactional data on minute-level.
The way we represent and use time-related information changes depending on the task. For a scientific experiment, we may talk about measurements recorded on microsecond-level. However, we do not need such a precision for demographic information such as population, average household income, and so on.
The datetime module of Python helps us handle time-related information on any precision level. In this article, we will elaborate on 4 objects in this module which are date, time, datetime, and timedelta.
Date
Date object represents a date in terms of year, month, and day. Let’s go over a few examples to demonstrate how to use them.
We can create a date object that stores a specific date by passing the year, month, and day information.
from datetime import date
mydate = date(2020, 4, 11)
print(mydate)
2020-04-11
We can also create a date object based on today’s date.
today = date.today()
print(today)
2021-04-13
It is possible to extract the individual attributes from a date object.
type(today)
datetime.date
today.year
2021
today.month
4
today.day
13
It is important to note that we cannot use leading zeroes on month and day information. For instance, the following code will return a syntax error.
mydate = date(2020, 04, 02) # SyntaxError
mydate = date(2020, 4, 2) # OK
Another useful method that we can use on a date object is ctime which returns the date in a more detailed or expanded format.
mydate = date(2021, 2, 15)
mydate.ctime()
Mon Feb 15 00:00:00 2021
We can calculate the difference between two dates using the minus sign.
mydate1 = date(2021, 2, 15)
mydate2 = date(2021, 3, 12)
mydate1 - mydate2
datetime.timedelta(days=-25)
The returned object is of type timedelta which we will also cover in this article. The difference is calculated in days.
Time
Time objects represent the time on hour, minute, second, and microsecond levels.
from datetime import time
mytime = time(14, 20)
print(mytime)
14:20:00
We have only defined the hour and minute part. Python assigns 0 for the remaining attributes of the time by default.
mytime.second
0
mytime.microsecond
0
We can also create more precise time objects by passing all the attributes.
mytime = time(2, 14, 25, 30)
print(mytime)
02:14:25.000030
Datetime
Datetime is kind of a combination of date and time. It can represent all the attributes from date and time objects. Let’s hop onto the examples to make it more clear.
from datetime import datetime
mydatetime = datetime(2021, 1, 14)
print(mydatetime)
2021-01-14 00:00:00
mydatetime2 = datetime(2021, 1, 14, 16, 20)
print(mydatetime2)
2021-01-14 16:20:00
The datetime object provides the flexibility of using date only, or date and time combined. There is a hierarchy among the parameters starting from year and going down to microsecond level.
The today function can be used with the datetime objects as well.
datetime.today()
datetime.datetime(2021, 4, 13, 16, 34, 45, 137530)
print(datetime.today())
2021-04-13 16:35:49.965258
If you print a datetime object, the output is displayed in a more structured way.
Just like with the date and time objects, individual attributes of the datetime objects can be extracted.
mydatetime = datetime(2021, 1, 14, 16, 20)
print(mydatetime.month)
1
print(mydatetime.minute)
20
We can calculate the difference between two datetime objects as well.
mydatetime1 = datetime(2021, 1, 14, 16, 20)
mydatetime2 = datetime(2021, 1, 10)
diff = mydatetime1 - mydatetime2
print(diff)
4 days, 16:20:00
Timedelta
Timedelta objects represent a duration so we can use them to calculate the difference between two dates or times.
Here is a timedelta object that represents a duration of 6 days.
mydelta = timedelta(days=6)
print(mydelta)
6 days, 0:00:00
We can create a timedelta object in terms of weeks, days, hours, minutes, seconds, and microseconds. The output is displayed in terms of days and hour-minute-second combination.
mydelta1 = timedelta(minutes=40)
print(mydelta1)
0:40:00
mydelta2 = timedelta(weeks=4)
print(mydelta2)
28 days, 0:00:00
Different units can be combined to create a timedelta object as well.
mydelta3 = timedelta(days=2, hours=4)
print(mydelta3)
2 days, 4:00:00
We have already seen how to calculate the difference between two date or datetime objects. Another common use case of timedelta objects is to modify them.
For instance, we can add a specific duration to a date to calculate a future date.
mydate = date.today()
print(mydate)
2021-04-13
two_weeks_from_now = mydate + timedelta(weeks=2)
print(two_weeks_from_now)
2021-04-20
We can also modify datetime objects using timedelta objects.
mydate = datetime(2020, 10, 4, 15, 10)
print(mydate)
2020-10-04 15:10:00
past_date = mydate - timedelta(weeks=7, days=4)
print(past_date)
2020-08-12 15:10:00
Conclusion
Datetime module of Python provides lots of different ways to manipulate dates and times. It comes in very handy when working with dates.
We have covered 4 main object types of the datetime module. These objects are date, time, datetime, and timedelta. The datetime object is kind of a combination of date and time objects. It can store information from year to microseconds.
The datetime module also provides some other object types such as timezone, strftime, and strptime.
Thank you for reading. Please let me know if you have any feedback.