Time slot availablity in python
Question: I am writing a slot booking algorithm for my application in python like this

    
    
    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
    

This works fine for me if i am checking slot for a particular date within 9
hours to 18 hours But it is not fulfilling my requirements for week or month
availability .Because i want to check availability for week or month between 9
hour to 18 hour .

Please help me to improve my code so that it could check the available slots
between 9 hours to 18 hours for weeks and months also.


Answer: I think you intend that `hours` applies to every day of the week or month
(except perhaps some days off?), so you might change it to use `time` objects.
Then for each day, you can `datetime.combine` to create an interval from the
previous day's end until this day's start. Don't forget to create one more
interval that starts at the last day's end.

