我正在像这样在 python 中为我的应用程序编写一个插槽预订算法
from datetime import datetime, timedelta
appointments = [(datetime(2012, 5, 22, 10), datetime(2012, 5, 22, 10, 30)),
(datetime(2012, 5, 22, 12), datetime(2012, 5, 22, 13)),
(datetime(2012, 5, 22, 15, 30), datetime(2012, 5, 22, 17, 10))]
hours = (datetime(2012, 5, 22, 9), datetime(2012, 5, 22, 18))
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
如果我在 9 小时到 18 小时内检查特定日期的时段,这对我来说很好,但它不能满足我对每周或每月可用性的要求。因为我想在 9 小时到 18 小时之间检查每周或每月的可用性。
请帮助我改进我的代码,以便它可以检查数周和数月的 9 小时到 18 小时之间的可用时段。