Python - finding time slots

筅森魡賤 提交于 2021-02-20 05:01:48

问题


I am writing a small Python script to find time available slots based off calendar appointments. I was able to reuse the code on the post here: (Python - Algorithm find time slots).

It does seem to work for booked appointments an hour or longer, but for those less than an hour it doesn't seem to catch them. In other words, it shows time slots as available even though appointments are booked (less than an hou).

Sample code below from post mentioned, with my own values for "hours" and "appointments".

#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)

When I run the script, I get:

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

The issue is that while the first appointment from 9:30-12:30 was blocked out and doesn't appear in available slots, the later 13:30-2:00 appointment was not blocked and therefore shows as available in the time slots output. (see "13:30 - 14:30").

I am a Python newbie and admit I recycled the code without fully understanding it. Can someone point me to what to change to make it properly block out the appointments less than hour?

TIA,

-Chris


回答1:


You missed the brackets in the appointments. Try this:

#from datetime import datetime, timedelta
import datetime

#notice the additional brackets to keep the 2 slots as two separate lists. So, 930-1230 is one slot, 1330-1400 is an another.

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))]


来源:https://stackoverflow.com/questions/46223664/python-finding-time-slots

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!