Karn Kumar
Karn Kumar

Reputation: 8816

Python Best Syntactic way of Calculating the age based on datetime

After searching around the web got the below two ways to get the age of a person. Just curious to Know if there is better synthetic way of calculating & writing it in 3.x version of python.

First way around ...

$ cat birth1.py
#!/grid/common/pkgs/python/v3.6.1/bin/python3
import datetime
year = datetime.datetime.now().year # getting current year from the system
year_of_birth = int(input("Enter Your Birth Year: "))
print("You are  %i Year Old" %  (year - year_of_birth))

The Result produced..

$ ./birth1.py
Enter Your Birth Year: 1981
You are  37 Year Old

Second way around ....

$ cat birth2.py
#!/grid/common/pkgs/python/v3.6.1/bin/python3
from datetime import datetime, date

print("Your date of birth (dd/mm/yyyy)")
date_of_birth = datetime.strptime(input("Please Put your age here: "), "%d/%m/%Y")

def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

age = calculate_age(date_of_birth)
print("You are  %i Year Old." %  (age))

The Result produces..

$ ./birth2.py
Your date of birth (dd/mm/yyyy)
Please Put your age here: 22/09/2015
You are  2 Year Old.

Upvotes: 1

Views: 106

Answers (1)

J_H
J_H

Reputation: 20435

Take advantage of timedelta.

import datetime as dt


def years_ago(start: str):
    sec_per_year = 365.24 * 24 * 60 * 60
    delta = dt.datetime.now() - dt.datetime.strptime(start, '%d/%m/%Y')
    return delta.total_seconds() / sec_per_year


if __name__ == '__main__':
    print(int(years_ago(input('What is your date of birth (dd/mm/yyyy) ? '))))

Upvotes: 1

Related Questions