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