You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何分析从数据库获取的元组格式日期并计算对应年龄?

实现方案

1. 核心逻辑说明

你之前尝试直接截取年份计算的方式会存在误差,比如当前日期未到当年生日时,计算出的年龄会比实际大1岁。我们通过datetime模块处理日期,同时兼容生日边界判断,结果更准确。
你之前调用datetime.strptime()失败大概率是格式匹配符写错,你拿到的日期是YYYY-MM-DD格式,对应的匹配符为%Y-%m-%d,注意%Y为大写,对应4位年份,%m、%d为小写,对应两位月份、日期即可匹配成功。

2. 完整代码实现

首先导入依赖模块,实现要求的age计算函数:

from datetime import datetime

def age(birth_date_str: str) -> int:
    # 将字符串格式的生日转为datetime对象
    birth_date = datetime.strptime(birth_date_str, "%Y-%m-%d")
    today = datetime.today()
    # 计算基础年份差
    calculated_age = today.year - birth_date.year
    # 若今年生日未到,年龄减1
    if (today.month, today.day) < (birth_date.month, birth_date.day):
        calculated_age -= 1
    return calculated_age

3. 业务逻辑调用

数据库读取代码优化

你原来从数据库读取日期的代码可以简化为列表推导式,更符合Python风格:

query_age = db.select([customer.columns.dob])
proxy_age = connection.execute(query_age)
result_age = proxy_age.fetchall()
# 一行代码替代循环append
date_list = [' '.join(row) for row in result_age]

批量计算年龄

直接用列表推导式调用age函数,即可得到所有日期对应的年龄列表:

ages = [age(date_str) for date_str in date_list]
print(ages)

如果不需要保留中间的日期列表,也可以合并为一步:

ages = [age(' '.join(row)) for row in result_age]

内容的提问来源于stack exchange,提问作者Arturo Altamirano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 21:45:04