TypeError: coercing to Unicode: need string or buffer, datetime.timedelta found

TypeError: coercing to Unicode: need string or buffer, datetime.timedelta found

我目前收到此错误

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 

我的代码:

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)

代码应输出如下内容:

09:00 - 10:00
10:30 - 11:30
13:00 - 14:00
14:00 - 15:00

我从

中找到了这段代码

您必须将 startend 字符串都转换为日期时间对象。请参阅以下示例:

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)