Search code snippets, questions, articles...

Get the number of days between two dates in Python

In this post, we are going to explain how to get the number of days between two days using Python code.
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)
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

Output

34

Here we are using Python datetime module to get the number of days. In the above code example:

  1. We have defined two date variables date_1 and date_2.
  2. Getting the number of using date_2 - date_1 syntax and assigning the result to num_of_days variable.
  3. Printing the result.

Format date and get the number of days

We are formatting the date in month/date/year format and then we are calculating the number of days.

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
Was this helpful?
0 Comments