【发布时间】:2018-02-23 16:58:14
【问题描述】:
我正在编写一个小型 Python 脚本来查找基于日历约会的可用时间段。我可以在这里重用帖子中的代码:(Python - Algorithm find time slots)。
对于一小时或更长时间的预约,它似乎确实有效,但对于不到一小时的预约,它似乎并没有抓住他们。换句话说,即使预约已被预订(不到一小时),它也会显示可用的时间段。
下面提到的帖子中的示例代码,带有我自己的“小时”和“约会”值。
#get_timeslots.py
from datetime import datetime, timedelta
appointments = [(datetime.datetime(2017, 9, 7, 9, 30),
datetime.datetime(2017, 9, 7, 12, 30),
datetime.datetime(2017, 9, 7, 13, 30),
datetime.datetime(2017, 9, 7, 14, 0))]
hours = (datetime.datetime(2017, 9, 7, 6, 0), datetime.datetime(2017, 9, 7, 23, 0))
def get_slots(hours, appointments, duration=timedelta(hours=1)):
slots = sorted([(hours[0], hours[0])] + appointments + [(hours[1], hours[1])])
for start, end in ((slots[i][1], slots[i+1][0]) for i in range(len(slots)-1)):
assert start <= end, "Cannot attend all appointments"
while start + duration <= end:
print "{:%H:%M} - {:%H:%M}".format(start, start + duration)
start += duration
if __name__ == "__main__":
get_slots(hours, appointments)
当我运行脚本时,我得到:
06:00 - 07:00
07:00 - 08:00
08:00 - 09:00
12:30 - 13:30
13:30 - 14:30
14:30 - 15:30
15:30 - 16:30
16:30 - 17:30
17:30 - 18:30
18:30 - 19:30
19:30 - 20:30
20:30 - 21:30
21:30 - 22:30
问题是,虽然 9:30-12:30 的第一个约会被阻止并且没有出现在可用空档中,但后来的 13:30-2:00 约会没有被阻止,因此显示为可用时隙输出。 (参见“13:30 - 14:30”)。
我是 Python 新手,我承认我在没有完全理解的情况下回收了代码。有人可以指出我要更改哪些内容以使其在不到一小时的时间内正确阻止约会吗?
TIA,
-克里斯
【问题讨论】:
标签: python