I'm looking to find overlapping dates between two dates ranges as the following:
range1 = start(2016-06-01) end (2016-06-20)
range2 = start(2016-06-10) end (2016-06-13)
result here is 4 dates (2016-06-10,2016-06-11,2016-06-12,2016-06-13)
.
another example:
range1 = start(2016-06-01) end (2016-06-20) range2 = start(2016-06-18)
end (2016-06-25)
result here is 3 dates (2016-06-18,2016-06-19,2016-06-20)
.
and if no dates overlap then the result is 0 dates.
I found this post its helpful in determining the number of overlapping dates but I was wondering if I can get the actual dates without using long if/else statements?
Thanks in advance!
I would suggest generating the dates in each of both ranges, then selecting the intersection between the two set. A snipped doing so may look like this:
from datetime import date, timedelta
def f(d1, d2):
delta = d2 - d1
return set([d1 + timedelta(days=i) for i in range(delta.days + 1)])
range1 = [date(2016, 6, 1), date(2016, 6, 20)]
range2 = [date(2016, 6, 10), date(2016, 6, 13)]
print f(*range1) & f(*range2)
For performance purposes you can also cast d1 + timedelta(days=i)
to str
while generating the dates in a given range.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With