AttributeError:' datetime.timedelta'对象没有属性' year'

时间:2018-02-08 11:53:43

标签: python python-3.x

d1 = datetime.strptime(self.current_date, "%Y-%m-%d")
d2 = datetime.strptime(self.dob, "%Y-%m-%d")

current_age = (d1 - d2).year

运行此代码会出现以下错误:

AttributeError: 'datetime.timedelta' object has no attribute 'year'

1 个答案:

答案 0 :(得分:5)

根据文档(https://docs.python.org/3/library/datetime.html),timedelta计算days,而非年数。请尝试(d1 - d2).days / 365.25

之类的内容