How to make age calculator in python


Here is a Python code that will calculate the age of a person based on their date of birth:
from datetime import datetime

def calculate_age(dob):
  # get the current year
  current_year = datetime.now().year

  # get the year of birth
  birth_year = dob.year

  # calculate the age
  age = current_year - birth_year

  # if the current month is before the month of birth, subtract 1 from the age
  if datetime.now().month < dob.month:
    age -= 1
  # if the current month is the same as the month of birth, but the current day is before the day of birth, subtract 1 from the age
  elif datetime.now().month == dob.month and datetime.now().day < dob.day:
    age -= 1

  return age

# get the date of birth from the user
dob_input = input("Enter your date of birth (YYYY-MM-DD): ")

# parse the date of birth from the input string
dob = datetime.strptime(dob_input, '%Y-%m-%d')

# calculate and print the age
age = calculate_age(dob)
print(f"Your age is: {age}")

This code will ask the user to input their date of birth in the format "YYYY-MM-DD", and it will then calculate and print their age based on the current date.


Post a Comment