from datetime import date
date_1 = date(2021, 7, 20)
date_2 = date(2021, 8, 23)
num_of_days = (date_2 - date_1).days
print(num_of_days)
Output
34
Here we are using Python datetime module to get the number of days. In the above code example:
We are formatting the date in month/date/year format and then we are calculating the number of days. We'll show you how to format dates in Python so that they're readable for humans, and how to calculate the number of days between two dates.
Code Example
from datetime import datetime
date_format = "%m/%d/%Y"
date_1 = datetime.strptime('10/25/2021', date_format)
date_2 = datetime.strptime('11/15/2021', date_format)
result = (date_2 - date_1).days
print(result)
Output
21
The syntax datetime.strptime(date_string, format) is used for converting date strings to datetime objects (i.e. datetime.datetime objects). The first argument is the date string that you want to convert, and the second argument is the date format that the date string is in. In this example, the date_string is in the format "MM/DD/YYYY".
The difference between two datetime objects (i.e. datetime.datetime objects) can be calculated using the syntax datetime_object_1 - datetime_object_2. The result is a datetime.timedelta object, which has an attribute called days, which is the number of days between the two datetime objects.
In this example, the difference between date_2 and date_1 is calculated, and the result (a datetime.timedelta object) is stored in the variable result. The days attribute of the result is then printed.
The below code snippet shows how to get the number of days from today to a particular date in python.
from datetime import datetime
today = datetime.today()
my_date = datetime.strptime("20/07/2022", "%d/%m/%Y")
date_diff = my_date - today
print("The number of days is: ", date_diff.days)
Output
The number of days is: 45
Line by line explanation of the above code example:
0 Comments