Datetime

Date arithmetic with timedelta

Once dates are real date or datetime values you can do math with them. timedelta represents a span of time. Add it to shift dates forward or backward, and subtract two dates to get the gap between them.


Once your dates are real datetime objects you can do math with them. The timedelta class represents a span of time, like 7 days or 90 minutes. Add it to shift dates around.

Build a timedelta and add it to a date:

Python
Output

timedelta accepts several keyword arguments. Pass any combination, including fractional values:

Python

What will be the output?

Python

Use a negative timedelta, or just subtract, to go backwards in time:

Python
Output

What will be the output?

Python

Subtract two date or datetime objects and you get a timedelta describing the gap. Read .days off it for an integer number of days.

Compute how many days between two dates:

Python
Output

What will be the output?

Python

Datetimes work the same way. Add a timedelta with hours and minutes to shift the time of day too.

A flight leaves at 14:00 and lasts 7h30m:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python