How to Calculate the Difference Between Two Dates

86 views

How to Calculate the Difference Between Two Dates

How to Calculate the Difference Between Two Dates

I need to find the difference in days between two dates. How can I do this in Python?

solveurit24@gmail.com Changed status to publish February 16, 2025
0

You can use the datetime module to handle dates and calculate the difference between them.

Code Example:

from datetime import datetime

def days_between_dates(date1_str, date2_str):
    date1 = datetime.strptime(date1_str, "%Y-%m-%d")
    date2 = datetime.strptime(date2_str, "%Y-%m-%d")
    delta = (date2 - date1).days
    return abs(delta)

# Example usage
date1 = "2023-10-01"
date2 = "2023-10-10"
print(days_between_dates(date1, date2))  # Output: 9 days

This function calculates the absolute difference in days between two dates provided in “YYYY-MM-DD” format.

solveurit24@gmail.com Changed status to publish February 16, 2025
0