gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 02:23:38 24 4
gpt4 key购买 nike

这是我的代码,它在第一次打印时工作正常,但给了我这个错误类型错误:必须是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com