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)}]
添加回答
舉報