0

我正在为 python 中的 time_slot 编写应用程序

请看这段代码

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, 24, 18))
duration = timedelta(minutes = 120)
def get_slots(hours, appointments,duration):

    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:
            dt_obj = start
            date_str = dt_obj.strftime("%Y-%m-%d %H:%M:%S")


            today18 = start.replace(hour=17, minute=59, second=59, microsecond=0)

            if start <  today18:
               print "{:%d:%H:%M} - {:%d:%H:%M}".format(start, start + duration)

               start += duration
            else:
               start += timedelta(hours = 15)
if __name__ == "__main__":
    get_slots(hours, appointments,duration)

当我像 python time_slots.py 一样运行上面的代码时,上面的代码对我来说工作正常

但是当我在 djanog 视图中使用上面的代码时

from datetime importdatetime ,timedelta 
    duration = timedelta(minutes = 60)
    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.datetime(2012, 5, 24, 18), datetime.datetime(2012, 5, 22, 9))
    hours = (datetime(2012, 5, 22, 9), datetime(2012, 5, 24, 18))
    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:

            today18 = start.replace(hour=17, minute=59, second=59, microsecond=0)

            if start <  today18:

               print "{:%H:%M} - {:%H:%M}".format(start, start + duration)

            else:
               start += timedelta(hours = 15)

当我调用这个视图时,它在控制台中返回一个无限循环

请帮助我在这里做错了什么我想要可用的时间段,因为我正在进入 time_slots.py

4

1 回答 1

1

在 Django 视图中,您忘记在if start < today18子句中添加要开始的持续时间。

于 2012-08-16T15:05:04.900 回答