
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:
- We import the
datetime
module to work with dates and times. - We ask the user to input two dates in the format ‘YYYY-MM-DD’ using the
input()
function. - We convert the input strings to
datetime
objects usingdatetime.strptime()
. - We calculate the difference between the two dates using subtraction, resulting in a
timedelta
object. - We extract the number of days from the
timedelta
object using the.days
attribute. - 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.