Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

current_age = (d1 - d2).year

Running this code give the following error:

AttributeError: 'datetime.timedelta' object has no attribute 'year'
like image 501
Supreeth KV Avatar asked Feb 08 '18 11:02

Supreeth KV


People also ask

How do I fix Attributeerror type object datetime datetime has no attribute datetime?

datetime' has no attribute 'datetime'. To resolve the problem, we just have to “import datetime” instead of “from datetime import datetime” as we did it above. Looks good.

What is datetime Timedelta in Python?

timedelta Objects. A timedelta object represents a duration, the difference between two dates or times. class datetime. timedelta (days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

How do I convert datetime to date in python?

The DateTime value is then converted to a date value using the dt. date() function.


1 Answers

As per the docs (https://docs.python.org/3/library/datetime.html), a timedelta counts days, not years. So try something like (d1 - d2).days / 365.25.

like image 51
John Zwinck Avatar answered Sep 29 '22 22:09

John Zwinck