This script calculates an age in years, months, and days from a given date of birth or determines an approximate birth date based on an exact age input.
The script utilizes the python-dateutil library, which extends Python’s standard datetime module by offering the relativedelta class for sophisticated date arithmetic; install it using pip3 install python-dateutil if it’s not already available.
Click to view script…
#!/usr/bin/env python3
from datetime import datetime
try:
from dateutil.relativedelta import relativedelta
except ImportError:
print("This script requires the 'python-dateutil' module. Install it via 'pip3 install python-dateutil'")
exit(1)
def calculate_age(birth_date, current_date):
"""Calculate the difference between two dates as (years, months, days) using relativedelta."""
delta = relativedelta(current_date, birth_date)
return delta.years, delta.months, delta.days
def main():
print("Select an option:")
print("1. Calculate an age from a date of birth")
print("2. Calculate a birth date from an exact age")
choice = input("Enter 1 or 2: ").strip()
today = datetime.today()
if choice == "1":
dob_str = input("Enter a date of birth (YYYY-MM-DD): ").strip()
try:
birth_date = datetime.strptime(dob_str, "%Y-%m-%d")
except ValueError:
print("Invalid date format. Please use YYYY-MM-DD.")
exit(1)
years, months, days = calculate_age(birth_date, today)
print(f"Calculated age: {years} years, {months} months, and {days} days.")
elif choice == "2":
print("Enter an exact age as three numbers separated by spaces.")
print("For example, if the age is 25 years, 4 months, and 15 days, type: 25 4 15")
age_input = input("Exact age (years months days): ").strip()
parts = age_input.split()
if len(parts) != 3:
print("Invalid input. Please enter three integers separated by spaces.")
exit(1)
try:
years = int(parts[0])
months = int(parts[1])
days = int(parts[2])
except ValueError:
print("Invalid input. Please ensure you enter numbers for years, months, and days.")
exit(1)
birth_date = today - relativedelta(years=years, months=months, days=days)
print("Calculated birth date is approximately:", birth_date.strftime("%Y-%m-%d"))
else:
print("Invalid option selected.")
if __name__ == '__main__':
main()