Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Doing Date and Time Arithmetic

The Python standard library provides the timedelta class for performing addition and subtraction on a datetime object. The third-party library dateutil has even more useful methods for doing this math.

00:00 In the previous lesson, I showed you the zoneinfo time zone database. In this lesson, I’ll be doing math on dates and times. I snuck a little math example into the previous lesson showing off the timedelta class.

00:15 This class allows you to add and subtract time to datetime objects, but it is a little bit limited as its upper time unit is days, which is why there are third-party libraries to augment it.

00:28 One of the more popular of the third-party libraries is called dateutil. This allows you to do larger relative deltas, specify recurrences, does some parsing, does some time zone stuff, and handles strange days like Easter in the Christian calendar.

00:45 As it is a third-party library, you need to do pip install to get it, and as with everything you pip install, it should be done inside of a virtual environment.

00:55 Let’s go do some datetime math in the REPL. I’ll start with the standard library’s timedelta class, importing it and a datetime object.

01:12 You’ve seen this before. So now I’ll create a delta.

01:19 This one stores a delta of a single day. The + (plus) in front of the 1 here isn’t strictly necessary, but it can make the code’s intent a little clearer.

01:31 I can use the delta and apply it to a datetime object. The result is exactly one day in the future, which of course is now in the past.

01:40 That’s the problem with demoing dates and times: eventually everything ends up in the past.

01:50 Time deltas can be negative as well. And in this case, the sum is the previous day. You can mix and match the arguments to affect both date and time in a timedelta().

02:12 And you can subtract as well. The limitation of timedelta() is the biggest time unit it handles is days. Third-party libraries to the rescue.

02:30 The dateutil library has a package called relativedelta that has a class with the same name. This is similar to the timedelta class and serves the same purpose.

02:40 Let me do tomorrow again …

02:49 or I can build something more complicated.

02:58 Notice the month change here. It was February 20, 2022, when I wrote this code. Nine more days would be the 29th. 2022 isn’t a leap year, so it cycles over to March 1st.

03:11 relativedelta knows all this stuff. Alternatively, you can give relativedelta two arguments to calculate a difference.

03:24 Here, I’m calculating the difference between now and now + delta. Nope, this doesn’t result in delta, because I put the now first, essentially doing subtraction. Let’s take all this new knowledge and update our BAKTUN script.

03:43 Lines 7 through 11 are the same as before. Let me just scroll down a bit. The new stuff starts around line 13. For starters, I’m using relativedelta to calculate the time difference. Lines 16 through 22 are really just to make the output prettier.

04:03 I’m looping through each of the attributes of the time difference and printing them out in human-readable form. This is instead of the hours:minutes:seconds output from the previous script.

04:16 The for loop is looping through six different time units. Line 17 gets the value of the corresponding time unit’s attribute inside of the relativedelta object. Lines 18 through 20 check if the unit is empty, and if it isn’t, check if the unit is 1.

04:33 If the unit is 1, the s gets stripped off the time_unit name. I was raised by a kindergarten teacher. 1 years grates me to no end.

04:45 Line 22 joins all the non-empty time_unit info into a string for printing on line 25. Line 24 adds a bit of extra stuff, printing the current date and time as well. Here, I’m using even more of the percent-based cryptic mini-language to format the output. Some of these you’ve seen before, some are new, unless you’re a keener and went and looked them all up. All right, let’s give this a whirl.

05:16 And there you go. %A and %B are the full spelling of the day of the week and the month. And the survival statement is far more informative. For a little homework, add a command-line argument that takes a time zone name and uses that in the delta instead of using the .astimezone() call.

05:37 That’s the key parts of doing dates and times in Python. Last stop, I’ll summarize and point you in some other places to further your investigation.

Become a Member to join the conversation.