这是我的代码,它适用于第一次打印,并给我这个错误 TypeError:必须是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
请有人告诉我为什么它起初工作正常然后我得到了那个错误
答案 0 :(得分:2)
它首次运行,因为tomorrow
是datetime.datetime
实例,然后是:
tomorrow = datetime.datetime.now()
然而,在第一次之后,您用字符串替换tomorrow
:
tomorrow = tomorrow.strftime('%d/%m/%Y')
您无法将timedelta()
对象添加到字符串中。不要重新绑定tomorrow
。将字符串分配给不同的名称,或者仅格式化对象以进行打印(而不是将其分配给名称):
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
答案 1 :(得分:0)
tomorrow = tomorrow.strftime('%d/%m/%Y')
将明天的类型更改为字符串,因此无法将其添加到datetime.timedelta。
而不是:
tomorrow = tomorrow + datetime.timedelta(days=1)
tomorrow = tomorrow.strftime('%d/%m/%Y')
...
print (tomorrow)
尝试:
tomorrow = tomorrow + datetime.timedelta(days=1)
...
print('{:%d/%m/%Y}'.format(tomorrow))