Let’s say that you have two dates:
"2019-01-29"
"2019-06-30"
Code language: JSON / JSON with Comments (json)
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 datetime
.
We start by importing the date
module.
from datetime import date
Code language: Python (python)
With this date module, we have access to an object format of the date
type.
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[0]), int(date1[1]), int(date1[2]))
date2_d = date(int(date2[0]), int(date2[1]), int(date2[2]))
# 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)
Code language: Python (python)
We created lists of our dates to be able to use them in the `date` function:
print( "2019-06-30".split("-") )
['2019', '06', '30']
Code language: Python (python)
As the 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
Code language: Python (python)