我有两个日期范围,每个范围都由开始日期和结束日期确定(显然,datetime.date()实例)。这两个范围可以重叠也可以不重叠。我需要重叠的天数。当然,我可以用两个日期范围内的所有日期预填充两个集合,并执行一个集合交集,但这可能效率不高…除了长距离的if- elif部分覆盖所有情况的解决方案,还有其他更好的方法吗?
这是一个示例计算:
>>> from datetime import datetime >>> from collections import namedtuple >>> Range = namedtuple('Range', ['start', 'end']) >>> r1 = Range(start=datetime(2012, 1, 15), end=datetime(2012, 5, 10)) >>> r2 = Range(start=datetime(2012, 3, 20), end=datetime(2012, 9, 15)) >>> latest_start = max(r1.start, r2.start) >>> earliest_end = min(r1.end, r2.end) >>> delta = (earliest_end - latest_start).days + 1 >>> overlap = max(0, delta) >>> overlap 52