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_diff - 1
else:
if month_diff >= 1:
years_old = year_diff
els

本文介绍了如何使用Python的datetime库来根据出生日期计算指定日期时的年龄,详细阐述了计算逻辑,并提供了相应的Python代码示例。
最低0.47元/天 解锁文章
1040

被折叠的 条评论
为什么被折叠?



