TypeError:必须为str,而不是datetime.timedelta [英] TypeError: must be str, not datetime.timedelta
问题描述
这是我的代码,它对于第一次打印可以正常工作,并给我这个错误TypeError:必须为str,而不是datetime.timedelta
here is my code it works fine for the first print and the give me this error TypeError: must be str, not 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
请有人告诉我为什么它先可以正常工作,然后我得到那个错误
please can someone tell me why it works fine at first then i get that error
推荐答案
它第一次起作用是因为明天
是 datetime.datetime
实例,然后:
It works the first time because tomorrow
is a datetime.datetime
instance then:
tomorrow = datetime.datetime.now()
但是,第一次之后,您将明天
替换为字符串:
However, after that first time, you replace tomorrow
with a string:
tomorrow = tomorrow.strftime('%d/%m/%Y')
您不能在字符串中添加 timedelta()
对象.不要重新绑定明天
.要么将字符串分配给其他名称,要么仅格式化对象以进行打印(而根本不将其分配给名称):
You can't add a timedelta()
object to a string. Don't rebind tomorrow
. Either assign the string to a different name, or only format the object for printing (and not assign it to a name at all):
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
这篇关于TypeError:必须为str,而不是datetime.timedelta的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!