Cover Image for Python Program to Find Number of Days Between Two Given Dates
129 views

Python Program to Find Number of Days Between Two Given Dates

You can find the number of days between two given dates in Python using the datetime module. Here’s a Python program that demonstrates how to do this:

from datetime import datetime

# Input the two dates as strings in the format 'YYYY-MM-DD'
date1_str = input("Enter the first date (YYYY-MM-DD): ")
date2_str = input("Enter the second date (YYYY-MM-DD): ")

# Convert the input strings to datetime objects
date1 = datetime.strptime(date1_str, "%Y-%m-%d")
date2 = datetime.strptime(date2_str, "%Y-%m-%d")

# Calculate the difference between the two dates
date_difference = date2 - date1

# Extract the number of days from the difference
num_days = date_difference.days

# Print the result
print(f"Number of days between {date1_str} and {date2_str}: {num_days} days")

In this program:

  1. We import the datetime module to work with dates and times.
  2. We ask the user to input two dates in the format ‘YYYY-MM-DD’ using the input() function.
  3. We convert the input strings to datetime objects using datetime.strptime().
  4. We calculate the difference between the two dates using subtraction, resulting in a timedelta object.
  5. We extract the number of days from the timedelta object using the .days attribute.
  6. Finally, we print the number of days between the two dates.

Make sure to enter the dates in the ‘YYYY-MM-DD’ format as specified in the input prompts.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS