Python Program To Get Days Between Two Dates
Chapter:
Python
Last Updated:
16-04-2023 12:21:33 UTC
Program:
/* ............... START ............... */
from datetime import datetime
date1_string = "2022-01-01"
date2_string = "2022-01-15"
date1 = datetime.strptime(date1_string, "%Y-%m-%d")
date2 = datetime.strptime(date2_string, "%Y-%m-%d")
days_between = abs((date2 - date1).days)
print(days_between)
/* ............... END ............... */
Output
14
> Because there are 14 days between January 1st and January 15th of 2022.
Notes:
-
In this example, we first define two dates as strings in the format "YYYY-MM-DD" using the variables date1_string and date2_string. In this case, date1_string is set to "2022-01-01" and date2_string is set to "2022-01-15".
- Next, we use the strptime method from the datetime module to parse the date strings and convert them into datetime objects. We store these objects in the variables date1 and date2.
- To calculate the number of days between the two dates, we subtract the earlier date from the later date and then use the days attribute to get the number of days between the two dates. We use the abs function to make sure that the result is always positive, regardless of which date is earlier.
- Finally, we print the number of days between the two dates to the console using the print function. In this case, the output will be "14"
Tags
Write a program in python to count the number of days between two dates #Python Program To Get Days Between Two Dates