Python Code to Calculate Age from Birthdate

If you would like to calculate your age in days or in years and days using Python, you can use the following code. The code requires your birthdate in the format YYYY-MM-DD as a command-line argument. For instance, if you saved the code as “calc_age.py“, you would run it like this:

python calc_age.py 2010-12-18

In the above command, your date with your birthdate.

This will display your age based on the provided birthdate. Feel free to copy and use the code as your personal age calculator. If you encounter any issues with the code, please don’t hesitate to let me know.

from datetime import date
import sys

def convert_days_to_years_and_days(total_days):
    """
    convert days to years and days -- leap year not considered
    """
    years = total_days // 365
    days = total_days % 365
    return years, days

def main():
    # get birthdate in yyyy-mm-dd format
    print("Enter date of birth in YYYY-MM-DD format as command line argument")
    args = sys.argv
    if len(args) < 2:
        print("no date of birth provided")
    else:
        dob  = args[1].split('-')
        birthday = date(int(dob[0]), int(dob[1]), int(dob[2]))

        # get the current date
        now = date.today()

        # compute age in days
        age = now - birthday
        print(f"your age is {age.days} days")

        # convert days into years and days
        yy, dd = convert_days_to_years_and_days(age.days)
        print(f"your age is approximately {yy} years and {dd} days.")

if __name__ == "__main__":
    main()
Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.