Get Started

Subtracting dates

Python date objects let us treat calendar dates as something similar to numbers: we can compare them, sort them, add, and even subtract them. This lets us do math with dates in a way that would be a pain to do by hand.

The 2007 Florida hurricane season was one of the busiest on record, with 8 hurricanes in one year. The first one hit on May 9th, 2007, and the last one hit on December 13th, 2007. How many days elapsed between the first and last hurricane in 2007?

This is a part of the course

“Working with Dates and Times in Python”

View Course

Exercise instructions

  • Import date from datetime.
  • Create a date object for May 9th, 2007, and assign it to the start variable.
  • Create a date object for December 13th, 2007, and assign it to the end variable.
  • Subtract start from end, to print the number of days in the resulting timedelta object.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Import date
from ____ import ____

# Create a date object for May 9th, 2007
start = date(____, ____, ____)

# Create a date object for December 13th, 2007
end = date(____, ____, ____)

# Subtract the two dates and print the number of days
print((____ - ____).____)

This exercise is part of the course

Working with Dates and Times in Python

IntermediateSkill Level
4.4+
36 reviews

Learn how to work with dates and times in Python.

Hurricanes (also known as cyclones or typhoons) hit the U.S. state of Florida several times per year. To start off this course, you'll learn how to work with date objects in Python, starting with the dates of every hurricane to hit Florida since 1950. You'll learn how Python handles dates, common date operations, and the right way to format dates to avoid confusion.

Exercise 1: Dates in PythonExercise 2: Which day of the week?Exercise 3: How many hurricanes come early?Exercise 4: Math with datesExercise 5: Subtracting dates
Exercise 6: Counting events per calendar monthExercise 7: Putting a list of dates in orderExercise 8: Turning dates into stringsExercise 9: Printing dates in a friendly formatExercise 10: Representing dates in different ways

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free