Let’s say that you have two dates:
How would you create a function that would return the number of days between these two dates?
Introducing the Datetime Package
Python comes with a built-in library called
We start by importing the
from datetime import date
With this date module, we have access to an object format of the
Writing our Function
Next, we should write our function that takes in two dates and returns the number of days between them.
from datetime import date # date1 = str # date2 = str # return = int def daysBetweenDates(date1, date2) -> int: # create list of of dates date1 = date1.split("-") date2 = date2.split("-") # create date objects from our list indices date1_d = date(int(date1), int(date1), int(date1)) date2_d = date(int(date2), int(date2), int(date2)) # get the amount of days between our two dates days = (date1_d - date2_d).days # return an absolute (positive) integer of the days return abs(int(days)
We created lists of our dates to be able to use them in the `date` function:
print( "2019-06-30".split("-") ) ['2019', '06', '30']
date function takes in integer values, we can now use the appropriate index locations of our date lists.
Testing our Function
Let’s test our function out:
print( daysBetweenDates("2019-01-29", "2019-06-30") ) # 152