根据出生日期计算年龄——基于Python的datetime库

1. 背景

基于出生日期,计算到指定日期时的年龄

2. 计算逻辑

给定出生日期,次年的同月同日及以后满1岁,否则不足1岁。

例如:1995年5月17日生,到1996年5月17日及以后则满1岁,到1996年5月16日时则不足1岁。

3. Python代码

from datetime import datetime

def age_calc(birth_date, end_date):
    # change the type of date to datetime
    birth_date = datetime.strptime(birth_date, '%Y-%m-%d')
    end_date = datetime.strptime(end_date, '%Y-%m-%d')

    # compute the difference of day, month and year
    day_diff = end_date.day - birth_date.day
    month_diff = end_date.month - birth_date.month
    year_diff = end_date.year - birth_date.year

    # compute age based on the diffference of day, month and year
    if day_diff >= 0:
        if month_diff >= 0:
            years_old = year_diff
        else:
            years_old = year_d
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值