how to find the number of years only using python

Viewed 315

I would like to make an age calculator, and I would like to find the number of years only, how can I achieve it based on the code I provide?

import datetime

print('birthday')
birthday=datetime.date(1997,7,1)
print(birthday)

print('today')
current=datetime.date.today()
print(current)

age=(current-birthday)//365
print('age')
print(age)

I expect the output should be 21 years, but the actual output is 21 days plus some unexpected info

3 Answers

It currently assumes you want to divide the number of days by 365. So the output is correct, just not the metric. Try and explicitly divide the number of days by 365 like so:

age = (current-birthday).days // 365
print(age)

Another way you could do this is using relativedelta from dateutil:

from dateutil.relativedelta import relativedelta
birthday = datetime.date(1997, 7, 1)
current = datetime.date.today()
rdelta = relativedelta(current, birthday)
print(rdelta.years)

This has the advantage of allowing you to print the months/days as well (rdelta.months/rdelta.days)

from datetime import date

d0 = date(2008, 8, 18)
d1 = date(2017, 9, 26)
delta = d1 - d0
print (delta.days/365.2422)

You don't need datetime for the calculation of age, just for determining the current date.

import datetime as dt

by, bm, bd = 1997, 7, 1
now = dt.date.today()

age = now.year - by
if (bm, bd) > (now.month, now.day):
    age -= 1    # hasn't had birthday this year

print(age)
Related