python - 类型错误 : must be str, 不是 datetime.timedelta

标签 python datetime

这是我的代码,它在第一次打印时工作正常,但给了我这个错误 类型错误:必须是 str,而不是 datetime.timedelta

import datetime
hour = datetime.datetime.now().hour
tomorrow = datetime.datetime.now()
for i in range(50):
    hour += 1
    print(hour)
    if hour >= 23:
        tomorrow = tomorrow + datetime.timedelta(days=1)
        tomorrow = tomorrow.strftime('%d/%m/%Y')
        hour = 9
        print (tomorrow)

这是输出:

13
14
15
16
17
18
19
20
21
22
23
07/12/2017
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Traceback (most recent call last):
  File "C:\Users\hamza.salhi\Desktop\datetime test.py", line 8, in <module>
    tomorrow = tomorrow + datetime.timedelta(days=1)
TypeError: must be str, not datetime.timedelta

请有人告诉我为什么它一开始工作正常然后我收到这个错误

最佳答案

它第一次起作用,因为 tomorrow 是一个 datetime.datetime 实例,然后:

tomorrow = datetime.datetime.now()

但是,在第一次之后,您将 tomorrow 替换为字符串:

tomorrow = tomorrow.strftime('%d/%m/%Y')

您无法将 timedelta() 对象添加到字符串中。 明天不要重新绑定(bind)。要么将字符串分配给不同的名称,要么仅格式化对象以进行打印(根本不将其分配给名称):

if hour >= 23:
    tomorrow = tomorrow + datetime.timedelta(days=1)
    tomorrow_formatted = tomorrow.strftime('%d/%m/%Y')
    hour = 9
    print(tomorrow_formatted)  # different name
    print(tomorrow.strftime('%d/%m/%Y'))  # print the `strftime()` result

关于python - 类型错误 : must be str, 不是 datetime.timedelta,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47672643/

相关文章:

python - 物联网中心事件 python

python - 无法使用包含空格和连字符的类名使用scrapy提取数据

python - 如何获取列中最频繁值的数量?

python - 我想比较叶子持续时间的日期与odoo python中的当前日期

java - 循环计算整周并跳过天数

c# - 在 C# 中获取 GetWeekOfYear 的日期?

python - 用 Python 编写解释器。 isinstance 是否被认为是有害的?

python - 提高 NeedDownloadError ('Need ffmpeg exe. ' NeedDownloadError : Need ffmpeg exe)

php - 将 unix 时间戳转换为 twitter/facebook 样式

c# - 将 float 转换为时间跨度