Write a python program to calculate the number of days between two dates
In this post, you will learn how to write a Python program to calculate the number of days between two dates.
Using the datetime module
Python provides an inbuilt datetime module. It has several classes which provide a number of functions to deal with dates, times and time intervals. To discover the difference between two dates, we simply input the two dates with date type and subtract them. By this we can simply get the number of days between the two dates.
# Python program to find number of days
# between two given dates
from datetime import date
def calNumOfDays(date1, date2):
return (date2-date1).days
# call function
date1 = date(2017, 9, 18)
date2 = date(2021, 7, 21)
print(calNumOfDays(date1, date2), "days")
Output of the above code:
1402 days
Using datetime.strptime()
Python strptime() is a class method in datetime class. It accepts the date format in the second argument.
# Python program to find number of days
# between two given dates
from datetime import datetime
#specify date format
date_format = "%Y-%d-%m"
a = datetime.strptime('1989-1-7', date_format)
b = datetime.strptime('2021-21-7', date_format)
delta = b - a
print(delta.days,"days")
Output of the above code:
11708 days
Related Articles
Python program to convert time from 12 hour to 24 hour format
Python class method vs static method
Bootstrap datepicker example
Python datetime formats and functions
Age calculator in Python
Pandas string to datetime
Convert Excel to CSV Python Pandas
Python program to display calendar
Python newspaper - Article scraping and curation
Python compare two lists
Remove element from list Python
Countdown clock and timer using Tkinter in Python
Python program to sum all the numbers in a list
Python print without newline
Python iterate list with index
Python add list to list
Python convert xml to dict
Python dict inside list
Python convert dict to xml
Python weather api
Python raise keyword