Home » How to find the number of days between two given dates in python

How to find the number of days between two given dates in python

1 Year Subscription
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer I [1Z0-815] Practice Tests
Oracle Java Certification
Spring Framework Basics Video Course
Java SE 11 Programmer II [1Z0-816] Practice Tests

In this example we look at how you can get the difference between two dates in days.

There are a couple of ways of doing this but by far the simplest way of doing this is by using the datetime module.

The process to find the difference between two dates is that we input the two dates with a date type and then subtract them, this provides us the number of days between the two dates.

Table of Contents

Example

# find number of days between two given dates
from datetime import date
 
def diffdays(date1, date2):
    return (date2-date1).days
     
# 2 dates
date1 = date(2020, 12, 25)
date2 = date(2022, 4, 10)

#print the diff
print(diffdays(date1, date2), "days")

Lets try this example out

>>> %Run diffdays1.py
471 days

Link

This is in our github repository

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More