0

我正在像这样在 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 小时之间的可用时段。

4

1 回答 1

0

我认为您打算将其hours应用于一周或一个月中的每一天(也许休息几天除外?),因此您可以将其更改为使用time对象。然后对于每一天,您可以datetime.combine创建从前一天结束到今天开始的间隔。不要忘记再创建一个从最后一天结束时开始的间隔。

于 2012-08-15T07:30:41.323 回答