# Date arithmetic with timedelta

You can't add two dates together, as that seldom makes sense. For example, what should happen if you add "today" to "today"?

import datetime

print(datetime.datetime.now() + datetime.datetime.now())
# Error

Instead, when you want to change a date—for example by adding a few days to it—we use the timedelta class. A "delta" in mathematics means a "change", so that's where the name comes from.

import datetime

today = datetime.datetime.now()
one_week = datetime.timedelta(days=7)

print(today + one_week) # 2019-12-30 11:58:52.073407

You can use timedelta with these arguments:

  • days
  • seconds
  • microseconds
  • milliseconds
  • minutes
  • hours
  • weeks

But the object itself will only store days, seconds, and microseconds. All other arguments will be converted to those (e.g. minutes * 60 will be added to seconds).

# Comparing datetime and timedelta

We also can't compare these two different objects. For example, the below is incorrect:

import datetime

today = datetime.datetime.now()
one_week = datetime.timedelta(days=7)

print(today > one_week) # Error, can't compare datetime and timedelta

Whenever I see code like that, usually the student writing this code meant to write this:

import datetime

today = datetime.datetime.now()
next_week = today + datetime.timedelta(days=7)

print(today > next_week) # False

Of course, the example above doesn't make much sense. Next week will always be greater than today.

This sort of comparison is useful when we're comparing "next week" to some user date:

import datetime

user_date = input("When will you paint your shed? ")
redecorate_date = datetime.datetime.strptime(user_date, "%d-%m-%Y")

next_week = datetime.datetime.now() + datetime.timedelta(days=7)

if redecorate_date > next_week:
    print("You're not painting within the next week. Slacker!")

I should take a thing or two from that script... My shed is in dire need!