Skip to main content
 首页 » 编程设计

python之属性错误 : 'datetime.timedelta' object has no attribute 'year'

2025年05月04日14sxdcgaq8080

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' 

请您参考如下方法:

根据文档(https://docs.python.org/3/library/datetime.html),timedelta 计算天,而不是年。所以尝试像 (d1 - d2).days/365.25 这样的东西。