My current application under test has an API with some dates. I need to calculate in some automated tests the days between two dates. Between the start and end date.
I created a function to calculate the number of days between two dates. The function has two input parameters. The two parameters are tuples with the year, month and day.
This means that 19 April 2000 results in the tuple (2000, 4, 19).
The function returns the number of days as a positive number. This means that I do not have to check which date is the latest date.
- days_between( (2020, 2, 17), (2010, 3, 1)) = 3640
- days_between( (2010, 3, 1), (2020, 2, 17) ) = 3640
It does not matter which parameter is placed where. Lets start coding.
from datetime import date def days_between(a, b): date1 = date(a,a,a) date2 = date(b,b,b) delta = date2 - date1 return abs(delta.days)
The function works like this:
- I create a date object. Create a date object with year, month and day as input arguments.
- Calculate the days between the two days.
- It is possible that the result is a negative value. To prevent that, the function returns the absolute value.
There is a built in function in python abs that does the trick.
I was not happy with the previous code. It can be better. I do not want to type all the arguments in the creation of the date object. Python has the asterisk operator. The documentation tells me this:
An asteriskThe python documentation
*denotes iterable unpacking. Its operand must be an iterable. The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.
This means that the program can be rewritten by this
from datetime import date def days_between(a, b): date1 = date(*a) date2 = date(*b) delta = date2 - date1 return abs(delta.days)
Now I can get rid of the variables date1 and date2:
from datetime import date def days_between(a, b): delta = date(*b) - date(*a) return abs(delta.days)
or in 1 line:
from datetime import date def days_between(a, b): return abs((date(*b) - date(*a)).days)
I wrote a function to calculate the days between two dates in python in with a few lines of code. I hope this tip is useful for you too.