import streamlit as st from datetime import datetime # Set the page config for the title and layout st.set_page_config(page_title="Age Calculator", layout="centered") # Title of the app st.title("Age Calculator") # Custom styles for a better look st.markdown(""" """, unsafe_allow_html=True) # Get user input for birthdate with st.form(key="age_calculator_form"): birth_date = st.date_input("Enter your birthdate", min_value=datetime(1950, 1, 1)) submit_button = st.form_submit_button("Calculate Age") # If form is submitted, calculate the age if submit_button: try: # Calculate the age today = datetime.today() years = today.year - birth_date.year months = today.month - birth_date.month days = today.day - birth_date.day # Adjust the months and days if needed (i.e., if today is earlier than the birthdate in a given year/month) if months < 0: months += 12 years -= 1 if days < 0: # Correct the number of days by subtracting from the previous month's days from datetime import timedelta last_month = today.replace(year=today.year, month=today.month) - timedelta(days=1) days += last_month.day months -= 1 if months < 0: months += 12 years -= 1 # Display the result st.success(f"You are **{years}** years, **{months}** months, and **{days}** days old!") st.write(f"Born on: {birth_date.strftime('%B %d, %Y')}") except Exception as e: st.error(f"Error: {str(e)}")