【问题标题】:TypeError: coercing to Unicode: need string or buffer, datetime.timedelta foundTypeError:强制转换为 Unicode:需要字符串或缓冲区,找到 datetime.timedelta
【发布时间】:2021-03-28 02:05:48
【问题描述】:

我目前收到此错误

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

我从Python - finding time slots找到了这段代码

【问题讨论】:

  • 您的代码导致TypeError: 'datetime.timedelta' object is not subscriptable - 不是您提到的错误
  • 我刚刚又检查了一遍。我仍然收到我提到的错误。
  • 这可能是因为我们使用不同的 python 发行版。无论如何,错误都是相似的。

标签: python python-3.x python-2.7 datetime typeerror


【解决方案1】:

您必须将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)

【讨论】:

    猜你喜欢
    • 2014-02-22
    • 2015-02-01
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    相关资源
    最近更新 更多