1 回答

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