When working with dates in Python, we often need to determine the difference between two dates. In this post, we’ll explore how to calculate the difference between two dates in days using Python’s datetime
module. Let’s dive in!
There are three steps:
- Step 1: Import the
datetime
Module : The first step is to import thedatetime
module, which comes built-in with Python. - Step 2: Create Date Objects : Next, you need to create
date
objects. You can create these objects by specifying the year, month, and day. - Step 3: Calculate the Difference : To find the difference between two dates, simply subtract one
date
object from another.
import datetime # Step 1: Import the datetime module from datetime import date # Step 2: Create date objects date1 = date(2023, 6, 15) date2 = date(2024, 6, 10) # Step 3: Calculate the difference difference = date2 - date1 # Step 4: Extract the difference in days days_difference = difference.days print(f"The difference between {date1} and {date2} is {days_difference} days.")
Output:
The difference between 2023-06-15 and 2024-06-10 is 361 days.