If you are not already working with Python3 and therefore cannot use memory-efficient range objects, you can do namedtuple as shown in the answer you are referencing (otherwise you could use the new range objects). From there, all you have to do is use datetime.date.fromordinal on an overlapping daterange:
>>> from datetime import date >>> from collections import namedtuple >>> Range = namedtuple('Range', ['start', 'end']) >>> r1 = Range(start=date(2016, 1, 1), end=date(2016, 2, 5)) >>> r2 = Range(start=date(2016, 1, 28), end=date(2016, 2, 28)) >>> latest_start = max(r1.start, r2.start) >>> earliest_end = min(r1.end, r2.end) >>> overlap = (earliest_end - latest_start).days + 1 >>> overlapping_dates = []
An approach using set will also work (one of these approaches is in this answer editing history), but is usually less efficient since it must have all dates in memory, even those that are not at the intersection.
source share