Often we'll be working with multiple datetime objects, and we'll want to compare them. The timedelta class is useful for finding the difference between two dates or times. While datetime objects represent a point in time, timedelta objects represents a duration, like 5 days or 10 seconds.
Suppose I want to know exactly how much older I am than my brother. I'll create datetime object for each of us representing the day and time of our birth.
my_birthday = datetime.datetime(1985, 10, 20, 17, 55)
brothers_birthday = datetime.datetime(1992, 6, 25, 18, 30)
Since we like to work with offset aware objects, we'll add timezone information.
indy = pytz.timezone("America/Indianapolis")
my_birthday = indy.localize(my_birthday)
brothers_birthday = indy.localize(brothers_birthday)
To see how much older I am than my brother, we can simply subtract the two datetime objects. And to see the answer in a human readable way, we can simple print the difference.
diff = brothers_birthday - my_birthday
> 2440 days, 0:35:00
The diff variable is actually a timedelta object that looks like this datetime.timedelta(2440, 2100).
Subtracting a datetime object from another yields a timedelta object, so as you might suspect, subtracting a timedelta object from a datetime object yields a datetime object.
datetime - datetime = timedelta
datetime - timedelta = datetime
Of course the same is true for addition.
This is useful for answering questions like "what was the date 3 weeks ago from yesterday?" or "what day of the week is 90 days from today?".
To answer the second question, we need to have two things - first, a datetime object representing today and second, a timedelta object representing 90 days.
today = datetime.datetime.now()
ninety_days = datetime.timedelta(days=90)
Then we can simply do the calculation.
target_date = today + ninety_days
And since we want to know the day of the week, we can use strftime.