python中有效的日期范围重叠计算? [英] Efficient date range overlap calculation in python?
本文介绍了python中有效的日期范围重叠计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
- 确定最后两个开始日期和最后两个结束日期。 li>
- 通过减去timedelta计算时间。
- 如果增量是正数,那就是重叠的天数。
以下是一个示例计算:
>> ; from datetime import datetime
>>>>从集合导入namedtuple
>>> Range = namedtuple('Range',['start','end'])
>>> r1 =范围(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)
>>> overlap =(earliest_end - latest_start).days + 1
>>>重叠
52
I have two date ranges where each range is determined by a start and end date (obviously, datetime.date() instances). The two ranges can overlap or not. I need the number of days of the overlap. Of course I can pre-fill two sets with all dates within both ranges and the perform a set intersection but this is possibly inefficient...is there a better way apart from another solution using a long if-elif section covering all cases ?
解决方案
- Determine the latest of the two start dates and the earliest of the two end dates.
- Compute the timedelta by subtracting them.
- If the delta is positive, that is the number of days of overlap.
Here is an example calculation:
>>> 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)
>>> overlap = (earliest_end - latest_start).days + 1
>>> overlap
52
这篇关于python中有效的日期范围重叠计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文