Age_Calculator / app.py
kaleempk's picture
Update app.py
7d046a2 verified
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("""
<style>
.stApp {
background-color: #f8f9fa;
font-family: 'Arial', sans-serif;
}
.title {
color: #007bff;
font-size: 36px;
font-weight: bold;
text-align: center;
}
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-top: 20px;
}
.form-container {
width: 100%;
max-width: 400px;
padding: 20px;
background-color: #ffffff;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
border-radius: 10px;
}
.error {
color: red;
}
</style>
""", 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)}")