Python Date Difference In Days
Chapter:
Python
Last Updated:
17-04-2023 13:22:57 UTC
Program:
/* ............... START ............... */
from datetime import datetime
date_format = "%Y-%m-%d" # format of the dates
date1_str = "2022-01-01"
date2_str = "2022-02-01"
date1 = datetime.strptime(date1_str, date_format) # convert string to datetime object
date2 = datetime.strptime(date2_str, date_format)
delta = date2 - date1 # difference between dates
print(delta.days) # prints the difference in days
/* ............... END ............... */
Output
If you run the program I provided with the date strings "2022-01-01" and "2022-02-01",
the output will be: 31
Notes:
-
To calculate the difference between two dates in Python in days, you can use the datetime module.
- The program is calculating the difference in days between two dates using the datetime module in Python.
- First, we define the format of the dates using the string "%Y-%m-%d". This specifies that the date string will be in the format of year-month-day.
- Next, we create two date strings date1_str and date2_str representing the dates we want to compare.
- Then, we use the strptime() method to convert the date strings into datetime objects. This method takes two arguments: the date string, and the format of the date string.
- After that, we compute the difference between the two dates by subtracting date1 from date2. This results in a timedelta object representing the difference between the two dates.
- Finally, we print the number of days between the two dates by accessing the days attribute of the timedelta object. This gives us the number of days between the two dates as an integer.