I will show you how to calculate your age in years, months, and days using Python. The script asks about the day, month, and year of your birthday and outputs the exact age. With some simple modifications, you can use the script for other datetime calculations.
import datetime birth_day = int(input("Day of birth: ")) birth_month = int(input("Month of birth: ")) birth_year = int(input("Year of birth: ")) day = int(datetime.date.today().day) month = int(datetime.date.today().month) year = int(datetime.date.today().year) if birth_year > year: age = year - birth_year else: age = (year - birth_year) - 1 b = abs(month - birth_month) c = abs(day - birth_day) print("Your age is:", age, "years", b, "months", c, "days")
The script first imports the Python datetime module. This module provides functions for working with dates and times.
The next three lines of code ask the user for their birthday date. The day, month, and year are then stored in the birth_day, birth_month, and birth_year variables.
The next three lines of code get the current date. The day, month, and year are then stored in the day, month, and year variables.
The next line of code checks if the birth year is greater than the current year. If it is, then the user is younger than one year old and the age is set to zero. Otherwise, the age is calculated as the difference between the current year and the birth year, minus one.
The next two lines of code calculate the number of months and days between the user’s birthday and the current date.
The final line of code prints the user’s age, number of months, and number of days.
Ideas to improve the script
Here are some ideas for how you can modify the script:
Calculate the age of someone else by asking for their birthday information.
Calculate the age of someone who was born on a specific date, such as your favorite celebrity or historical figure.
Calculate the number of days, weeks, or months until your next birthday.
Calculate the number of years, months, or days since a specific event, such as your wedding day or the day you graduated from college.
You learned how to calculate your age in years, months, and days using Python. The script is a simple way to calculate your age, but it can be modified to calculate the age of other people or to perform other datetime calculations.