年龄计算器
根据出生日期精确计算年龄(年、月、日)。
关于此工具
年龄计算器是一个简单的工具,通过比较您的出生日期和今天的日期来精确计算您的年龄,精确到天。了解自己的确切年龄(以年、月、日为单位)对官方文件、健康记录、资格验证和人生重要里程碑都很重要。这个计算器省去了手工计算的麻烦,消除了出错的风险,瞬间为您提供准确的答案。
使用时,只需在提供的字段中输入您的出生日期,然后点击计算按钮。该工具会立即显示您的年龄,分解为年、月、日的形式;如果需要更详细的信息,还能显示以周、天或小时为单位的确切年龄。常见的用途包括检查年龄限制服务的资格、验证表格信息、追踪人生重要事件过去的时间长度,以及满足对自己确切年龄的好奇心。
常见问题
代码实现
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.