We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Datetime Math

Once you've parsed a date or timestamp, you usually want to do something with it. You might want to know:

  • How long has an order been in transit?
  • When should the package arrive?

That's where timedelta comes in.

Working with data is all about answering real questions. You can't do data work without a goal in mind, or you'll just be shuffling numbers around.

Date Difference

Subtract one datetime from another and you get a timedelta:

order_placed = datetime(2026, 5, 25, 14, 30, 0)
delivered_at = datetime(2026, 5, 29, 14, 30, 0)
difference = delivered_at - order_placed  # difference is a timedelta object
print(difference.days)  # the .days is... exactly what you expect
# 4

Adding Time

You can also add or subtract a timedelta from a datetime to get a new datetime:

order_placed = datetime(2026, 5, 25, 14, 30, 0)
expected_by = order_placed + timedelta(hours=6)
print(expected_by)
# 2026-05-25 20:30:00

Assignment

SnackStack considers a device's reading "stale" if it stays quiet for too long.

Complete the calculate_stale_time function. It accepts a "reading_time" datetime and the maximum number of hours the device can stay silent, and returns a new datetime object representing the time when the reading will become stale.

Use the timedelta function to add max_silent_hours to the reading timestamp and return the result.