python中有效的日期范围重叠计算? [英] Efficient date range overlap calculation in python?

查看:173
本文介绍了python中有效的日期范围重叠计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个日期范围,每个范围由开始和结束日期确定(显然,datetime.date()实例)。两个范围可以重叠。我需要重叠的天数。当然,我可以预先填写两个范围内的所有日期的两个集合,并且执行一个设置的交集,但是这可能是低效的?除了另一个解决方案之外,还有一个更好的方法,使用一个长的if-elif部分涵盖所有情况? / p>

解决方案


  • 确定最后两个开始日期和最后两个结束日期。 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆