Python Program To Calculate Age In Years Months And Days
Chapter:
Python
Last Updated:
16-09-2023 06:37:09 UTC
Program:
/* ............... START ............... */
from datetime import datetime
def calculate_age(birthdate):
# Get the current date
current_date = datetime.now()
# Calculate the age
age = current_date - birthdate
# Extract years, months, and days from the age
years = age.days // 365
months = (age.days % 365) // 30
days = (age.days % 365) % 30
return years, months, days
# Input the birthdate in the format yyyy, mm, dd
year = int(input("Enter the birth year: "))
month = int(input("Enter the birth month: "))
day = int(input("Enter the birth day: "))
birthdate = datetime(year, month, day)
years, months, days = calculate_age(birthdate)
print(f"Age: {years} years, {months} months, {days} days")
/* ............... END ............... */
Output
/* This is sample output */
Enter the birth year: 1990
Enter the birth month: 5
Enter the birth day: 15
Age: 33 years, 4 months, 1 days
Notes:
-
First We import the datetime module to work with dates.
- The calculate_age function takes the birthdate as input and calculates the age in days.
- We then extract years, months, and days from the age in days.
- Finally, we take user input for the birthdate, create a datetime object, and call the calculate_age function to get the age in years, months, and days, which we then print.
- Make sure to enter the birth year, month, and day as integers when prompted.
Tags
Python program to calculate age in years months and days #Python program to calculate age in year #How do you calculate age in Python?