from datetime import datetime, date import re def parse_date(date_str): “””Parse dates in various formats into datetime.date object””” # Try common date formats formats = [ ‘%Y-%m-%d’, # YYYY-MM-DD ‘%m/%d/%Y’, # MM/DD/YYYY ‘%d-%m-%Y’, # DD-MM-YYYY ‘%Y/%m/%d’, # YYYY/MM/DD ‘%d %b %Y’, # DD Mon YYYY ‘%d %B %Y’, # DD Month YYYY ] for fmt in formats: try: return datetime.strptime(date_str, fmt).date() except ValueError: continue # Try to handle dates without leading zeros (e.g., 1/1/2023) if re.match(r’^\d{1,2}[/-]\d{1,2}[/-]\d{4}$’, date_str): parts = re.split(r'[/-]’, date_str) try: month = int(parts[0]) day = int(parts[1]) year = int(parts[2]) return date(year, month, day) except (ValueError, IndexError): pass return None def is_valid_date(birth_date, current_date): “””Validate the birth date””” if birth_date is None: return False, “Error: Please enter a valid birthdate.” if birth_date > current_date: return False, “Error: Birthdate cannot be in the future.” return True, “” def calculate_age(birth_date, current_date): “””Calculate age in years, months, and days””” years = current_date.year – birth_date.year months = current_date.month – birth_date.month days = current_date.day – birth_date.day # Handle negative months/days if days < 0: # Get the last day of the previous month last_day_of_prev_month = (current_date.replace(day=1) - timedelta(days=1)).day days += last_day_of_prev_month months -= 1 if months < 0: months += 12 years -= 1 return years, months, days def age_calculator(birthdate_str, currentdate_str=None): """Main age calculator function""" # Parse dates birth_date = parse_date(birthdate_str) if currentdate_str: current_date = parse_date(currentdate_str) if current_date is None: return "Error: Please enter a valid current date." else: current_date = date.today() # Validate dates valid, message = is_valid_date(birth_date, current_date) if not valid: return message # Calculate age years, months, days = calculate_age(birth_date, current_date) return f"You are {years} years, {months} months, and {days} days old." # Example usage if __name__ == "__main__": print("Age Calculator") print("Enter your birthdate (format: YYYY-MM-DD or MM/DD/YYYY or DD-MM-YYYY etc.)") while True: birthdate_input = input("Birthdate: ").strip() currentdate_input = input("Current date (optional, press Enter to use today's date): ").strip() if currentdate_input == "": result = age_calculator(birthdate_input) else: result = age_calculator(birthdate_input, currentdate_input) print(result) another = input("Calculate another age? (y/n): ").strip().lower() if another != 'y': break

Leave a Reply

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