首页 › Python 实例 › 根据生日计算年龄

Python 根据生日计算年龄

日期与文件实例 034

题目

根据出生日期和参考日期计算周岁年龄,以及距离下一次生日还有多少天。

参考代码

from datetime import date

def age_on(birthday, today):
    years = today.year - birthday.year
    if (today.month, today.day) < (birthday.month, birthday.day):
        years -= 1
    return years

def days_to_birthday(birthday, today):
    nxt = birthday.replace(year=today.year)
    if nxt < today:
        nxt = nxt.replace(year=today.year + 1)
    return (nxt - today).days

today = date(2026, 11, 19)
for b in [date(2000, 5, 20), date(1995, 12, 1), date(2010, 11, 19)]:
    print(f"生日 {b}:{age_on(b, today)} 岁,距下次生日 {days_to_birthday(b, today)} 天")
执行以上代码输出结果为:
生日 2000-05-20:26 岁,距下次生日 182 天
生日 1995-12-01:30 岁,距下次生日 12 天
生日 2010-11-19:16 岁,距下次生日 0 天

代码解析

比较 (月, 日) 元组可以判断今年的生日是否已经过去。这里为了结果可复现,把"今天"固定为 2026-11-19,实际使用时改为 date.today()。