TypeError:无法隐式地将'datetime.timedelta'对象转换为str

时间:2017-02-22 17:55:02

标签: python datetime

伙计们,我是Python的新手,我在运行这段代码时看到了这个错误(如下所示),我做错了什么?

from datetime import datetime
from datetime import timedelta

date = (datetime.today().strftime("%m/%d/%y"))
new_date = date + timedelta(days=10)
print(new_date)

ERROR:

    new_date = date + timedelta(days=10)
TypeError: Can't convert 'datetime.timedelta' object to str implicitly

1 个答案:

答案 0 :(得分:1)

您将datetime对象转换为字符串:

>>> from datetime import datetime
>>> datetime.today().strftime("%m/%d/%y")
'02/22/17'

您无法对字符串和timedelta对象求和。您可能想要获得datetime.date()对象:

from datetime import date, timedelta

today = date.today()
print(today + timedelta(days=10))

或使用datetime.date() method提取日期:

today = datetime.today().date()
print(today + timedelta(days=10))

如果您仍然需要字符串对象,请在应用日期算术后转换

future = today + timedelta(days=10)
print(future.strftime('%m/%d/%y'))