Reputation: 129
im currently getting this error
Traceback (most recent call last):
File "/Users/user/Documents/test.py", line 44, in <module>
get_slots(hours, appointments)
File "/Users/user/Documents/test.py", line 36, in get_slots
while start + duration <= end:
TypeError: coercing to Unicode: need string or buffer, datetime.timedelta found
My code:
from datetime import 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.
# HOURS AND APPOINTMENTS ARE GENERATED BY GATHERING DATA FROM DATABASE
hours = [[u'08:00', u'17:00']]
appointments = [(u'12:00', u'12:30'), (u'10:30', u'11:00')]
def get_slots(hours, appointments, duration=timedelta(hours=1)):
slots = sorted([(hours[0][0], hours[0][0])] + appointments + [(hours[0][1], hours[0][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:
json = []
json.append("{:%H:%M} - {:%H:%M}".format(start, start + duration))
start += duration
return json
if __name__ == "__main__":
get_slots(hours, appointments)
The code should output something like:
09:00 - 10:00
10:30 - 11:30
13:00 - 14:00
14:00 - 15:00
I found this code from Python - finding time slots
Upvotes: 0
Views: 574
Reputation: 5476
You have to convert both start
and end
string to datetime objects. See below example:
from datetime import 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.
# HOURS AND APPOINTMENTS ARE GENERATED BY GATHERING DATA FROM DATABASE
hours = [[u'08:00', u'17:00']]
appointments = [(u'12:00', u'12:30'), (u'10:30', u'11:00')]
def get_slots(hours, appointments, duration=timedelta(hours=1)):
slots = sorted([(hours[0][0], hours[0][0])] + appointments + [(hours[0][1], hours[0][1])])
for start, end in ((slots[i][1], slots[i+1][0]) for i in range(len(slots)-1)):
start = datetime.datetime.strptime(start, "%H:%M")
end = datetime.datetime.strptime(end, "%H:%M")
print(start+duration)
assert start <= end, "Cannot attend all appointments"
while start + duration <= end:
json = []
json.append("{:%H:%M} - {:%H:%M}".format(start, start + duration))
start += duration
return json
if __name__ == "__main__":
x = get_slots(hours, appointments)
Upvotes: 1