🛠️ToolsShed

나이 계산기

생년월일로 정확한 나이를 년, 월, 일로 계산.

자주 묻는 질문

코드 구현

from datetime import date

def calculate_age(birthdate: date, today: date = None) -> dict:
    """Calculate age in years, months, and days."""
    if today is None:
        today = date.today()
    years = today.year - birthdate.year
    months = today.month - birthdate.month
    days = today.day - birthdate.day
    if days < 0:
        months -= 1
        # Days in the previous month
        prev_month = today.replace(day=1)
        import calendar
        days_in_prev = calendar.monthrange(prev_month.year, prev_month.month - 1 or 12)[1]
        days += days_in_prev
    if months < 0:
        years -= 1
        months += 12
    return {"years": years, "months": months, "days": days}

# Example
birth = date(1990, 6, 15)
age = calculate_age(birth)
print(f"Age: {age['years']} years, {age['months']} months, {age['days']} days")

total_days = (date.today() - birth).days
print(f"Total days lived: {total_days}")

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.