Days between two dates

Days between two dates

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[0],a[1],a[2])
    date2 = date(b[0],b[1],b[2])
    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.

Refactor

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 asterisk * 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.

The python documentation

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)

Conclusion

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.

About the author

I currently work as a Test Automation Consultant at b.ignited. Here I work for different clients in different industries to help them start and speed up their testing cycles

I’ve been testing software since 2000 when I became involved in testing telephone applications and hardware. Since then, I’ve been able to expand my experience by testing a variety of embedded, web, mobile and desktop applications. I have used various development methodologies from waterfall to agile.

I consider myself to be a lifelong learner.