Reputation: 307
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'
Upvotes: 11
Views: 37341
Reputation: 1668
Calculating the difference between 2 dates returns a timedelta (datetime.timedelta
) such as (d1 - d2)
in your sample code ("A timedelta object represents a duration, the difference between two dates or times."). Available from this are .days
, .seconds
and .microseconds
(only). A timedelta
isn't anchored to particular years so it doesn't provide .years
since the number of leap years can only be accurately counted once a start date is known (timedelta
doesn't have this information). Using the Python REPL,
>>> import datetime
>>> datetime.date(2021,1,1) - datetime.date(2020,1,1)
datetime.timedelta(days=366)
>>> datetime.date(2022,1,1) - datetime.date(2021,1,1)
datetime.timedelta(days=365)
For an exact answer take the original dates' year
values and then use their month
and day
values to work out whether the subject's birthday has occurred this year or not. Adapting your sample code and omitting reference to the class you're clearly using (you don't provide the code for that so it's confusing to include it),
from datetime import date
d1 = date.today()
d2 = date(2000, 1, 1) # Example date
current_age = d1.year - d2.year
if (d1.month, d1.day) < (d2.month, d2.day):
current_age = current_age - 1 # Not had birthday yet
print(current_age)
Alternatively use the dateutil
module's relativedelta
which is aware of years. For example,
from datetime import date
from dateutil.relativedelta import relativedelta
d1 = date.today()
d2 = date(2000, 1, 1) # Example date
current_age = relativedelta(d1, d2).years
print(current_age)
Upvotes: 6
Reputation: 249123
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
.
Upvotes: 29