萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

Python 根據出生日期精確計算年齡與下次生日倒計時

核心函數

from datetime import date, datetime

def calculate_age(birth_str, fmt='%Y.%m.%d'):
    """返回 (年齡, 距下次生日天數, 下次生日日期)"""
    try:
        birth = datetime.strptime(birth_str, fmt).date()
    except ValueError:
        return None, None, None
    
    today = date.today()
    
    # 今年生日
    this_year_bday = date(today.year, birth.month, birth.day)
    
    # 年齡計算
    age = today.year - birth.year
    if today < this_year_bday:
        age -= 1  # 尚未過生日
    
    # 下次生日
    if today <= this_year_bday:
        next_bday = this_year_bday
    else:
        next_bday = date(today.year + 1, birth.month, birth.day)
    
    days_left = (next_bday - today).days
    
    return age, days_left, next_bday

# 測試
print(calculate_age('2000.05.05'))  # (23, 45, datetime.date(2024, 5, 5))
print(calculate_age('1990.12.25'))  # (33, 280, datetime.date(2024, 12, 25))

邊界情況處理

  • 閏年 2 月 29 日:非閏年按 2 月 28 日或 3 月 1 日計算(按業務規則)
  • date.replace(year=...) 會在 2/29 非閏年拋 ValueError,需捕獲調整

健壯版(處理閏年)

def safe_birthday(birth, year):
    try:
        return birth.replace(year=year)
    except ValueError:
        # 2月29日 -> 2月28日
        return birth.replace(year=year, day=28)

def calculate_age_safe(birth_str, fmt='%Y-%m-%d'):
    birth = datetime.strptime(birth_str, fmt).date()
    today = date.today()
    
    bday_this = safe_birthday(birth, today.year)
    bday_next = safe_birthday(birth, today.year + 1)
    
    if today < bday_this:
        age = today.year - birth.year - 1
        next_bday = bday_this
    else:
        age = today.year - birth.year
        next_bday = bday_next if today >= bday_this else bday_this
    
    return age, (next_bday - today).days, next_bday

應用場景

  • 用戶畫像:年齡段分佈統計
  • 生日營銷:提前 N 天推送優惠券
  • 保險/金融:精確計算保齡、滿期日期
copyright © 萬盛學電腦網 all rights reserved