Write a Python program to calculate number of days between two dates
In this post, you will learn how to calculate the number of days between two dates using the Python programming language.
For this, we need to define two dates between which you want to find the difference in days. Python provides the datetime module for creating or manipulating dates and times.
ExamplesInput : date1 = 21/3/2021, date2 = 16/11/2021
Output : 240 days
Input : date1 = 3/11/2020, date2 = 21/9/2021
Output : 322 days
Python subtracting date objects
In the given Python program, we have stored the dates in two variables and subtracted these dates to get a timedelta object.
# Importing the datetime module
from datetime import date
#Initilizing dates
date1 = date(2021, 3, 21)
date2 = date(2021, 11, 16)
# calculating number of days
delta = date2 - date1
print("Number of days: ",delta.days)
Output of the above code:
Number of days: 240
Using datetime.strptime()
Python provides a standard library for date and time formats. The Datetime module of Python supplies classes to work with date and time. These classes provide a number of functions to deal with dates, times, and time intervals. The strptime() method creates a date object from the given string, which in turn can be subtracted from another date object to get "timedelta" object.
# Importing the datetime module
from datetime import datetime
#specify date format
date_format = "%m/%d/%Y"
#Initilizing dates
a = datetime.strptime('11/03/2020', date_format)
b = datetime.strptime('9/21/2021', date_format)
# calculating number of days
delta = b - a
print("Number of days: ",delta.days)
Output of the above code:
Number of days: 322
Related Articles
Convert Python list to numpy arrayConvert string to list Python
Python program to list even and odd numbers of a list
Python loop through list
Sort list in descending order Python
Convert array to list Python
Python take screenshot of specific window
Web scraping Python BeautifulSoup
Check if two strings are anagrams Python
Python program to add two numbers
Print new line python
Python for loop index
Convert List to Dataframe Python
numpy random choice
Dictionary inside list python
Check if list is empty Python
Python raise keyword
Python program to get the largest number from a list
Python program to map two lists into a dictionary