Get days between two dates

Scenario: Sometimes you need to calculate the number of days between current date and a future or past date. You can directly perform subtraction between dates. When you subtract a date (D2) from another date(D1), the output will be a negative number if D2 > D1.

 

Example: calculate number of days between current date and a date stored in the DB.

>>> lastPackageDetails = PurchaseHistory.objects.filter(customer=43).last()

>>> lastPackageDetails = lastPackageDetails[0]

>>> expiryDate = lastPackageDetails.expiry_date.date()  # expiry_date column is datetime in the DB, so we need to apply date() on expiry_date to convert datetime to date

datetime.date(2020, 3, 19)

 

>>> currentDate = datetime.datetime.now().date()

datetime.date(2020, 3, 18)

 

>>> delta = expiryDate – currentDate;

>>> delta.days

1

 

>>> userDefinedDate = datetime.date(2020, 3, 21) # custom date as current date

>>> delta = expiryDate – userDefinedDate;

>>> delta.days

-2

Number of days between expiryDate and userDefinedDate are 2. Negative symbol shows that the userDefinedDate is the date after the expiryDate.

 

>>> type(delta.days)

<class ‘int’>

Add days to a date

>>> expiryDate

datetime.date(2020, 3, 19)

>>> expiryDate + datetime.timedelta(days=1)

datetime.date(2020, 3, 20)

 

>>> expiryDate + datetime.timedelta(days=2)

datetime.date(2020, 3, 21)

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top
Shares