猿问

给定许多“开始”和“结束”日期时间对象,如何找到间隙?

我有成对的 DateTime 对象。每个 DateTime 对象都是时间范围的“开始”或“结束”。时间范围有时会重叠。我需要找到差距。


我在 pypi 上尝试了 DateTimeRange 模块,测试相交范围,然后构建包含的范围(根据他们的文档),但我无法将这些组件构建到一段代码中来做我想要的


编辑:在这种情况下,“间隔”被定义为最早的“开始”和最新的“结束”之间的任何时间段,该时间段不包含在“开始”和“结束”DateTime 对象对中


import dateparser

from pprint import pprint


foo = []


foo.append({

    "start": dateparser.parse("8:00 AM"),

    "end": dateparser.parse("8:06 AM")

})


foo.append({

    "start": dateparser.parse("8:03 AM"),

    "end": dateparser.parse("8:07 AM")

})


foo.append({

    "start": dateparser.parse("8:02 AM"),

    "end": dateparser.parse("8:16 AM")

})


foo.append({

    "start": dateparser.parse("8:20 AM"),

    "end": dateparser.parse("8:30 AM")

})


pprint(foo)


#[{'end': datetime.datetime(2019, 2, 15, 8, 6),

#  'start': datetime.datetime(2019, 2, 15, 8, 0)},

# {'end': datetime.datetime(2019, 2, 15, 8, 7),

#  'start': datetime.datetime(2019, 2, 15, 8, 3)},

# {'end': datetime.datetime(2019, 2, 15, 8, 16),

#  'start': datetime.datetime(2019, 2, 15, 8, 2)},

# {'end': datetime.datetime(2019, 2, 15, 8, 30),

#  'start': datetime.datetime(2019, 2, 15, 8, 20)}]



find_gaps(foo)


#desired output

#

#[{'end': datetime.datetime(2019, 2, 15, 8, 20),

#  'start': datetime.datetime(2019, 2, 15, 8, 16)}]



扬帆大鱼
浏览 177回答 1
1回答

慕桂英3389331

您可以根据开始时间对范围进行排序,然后跟踪结束时间,直到找到结束时间和下一个开始时间之间的差距。如果你发现这个差距,你就追加它。如果下一个结束时间大于当前结束时间,则需要提前结束时间。def find_gaps(ranges):&nbsp; &nbsp; if len(ranges) <= 1:&nbsp; &nbsp; &nbsp; &nbsp; return []&nbsp; &nbsp; # sort by start times&nbsp; &nbsp; ranges = sorted(ranges, key=lambda x:x['start'])&nbsp; &nbsp; gaps = []&nbsp; &nbsp; # Start at the end of the first range&nbsp; &nbsp; now = ranges[0]['end']&nbsp; &nbsp; # Iterate through ranges, ignoring the first range&nbsp; &nbsp; for pair in ranges[1:]:&nbsp; &nbsp; &nbsp; &nbsp; # if next start time is before current end time, keep going until we find a gap&nbsp; &nbsp; &nbsp; &nbsp; # if next start time is after current end time, found the first gap&nbsp; &nbsp; &nbsp; &nbsp; if pair['start'] > now:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; gaps.append({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'start':now,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'end':pair['start']&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; # need to advance "now" only if the next end time is past the current end time&nbsp; &nbsp; &nbsp; &nbsp; now = max(pair['end'], now)&nbsp; &nbsp; return gaps输出:[{'end': datetime.datetime(2019, 2, 15, 8, 20),&nbsp; 'start': datetime.datetime(2019, 2, 15, 8, 16)}]
随时随地看视频慕课网APP

相关分类

Python
我要回答