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.pyfrom datetime import datetime, timedeltaappointments = [(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 += durationif __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