1、测试
import pandas as pd
import datetime
temp_data='110221195404083625'
v_start_date=temp_data[6:14]
now = datetime.datetime.now()
now = now.strftime('%Y%m%d')
v_year_end=datetime.datetime.strptime(now, '%Y%m%d').year
v_month_end=datetime.datetime.strptime(now, '%Y%m%d').month
v_day_end=datetime.datetime.strptime(now, '%Y%m%d').day
v_year_start=datetime.datetime.strptime(v_start_date, '%Y%m%d').year
v_month_start=datetime.datetime.strptime(v_start_date, '%Y%m%d').month
v_day_start=datetime.datetime.strptime(v_start_date, '%Y%m%d').day
#1、若今天的月大于生日的月,年龄=今年的年-生日的年
if v_month_end>v_month_start:
age=v_year_end-v_year_start
#2、若今天的月小于生日的月,年龄=今年的年-生日的年-1
elif v_month_end<v_month_start:
age=v_year_end-v_year_start-1
#3、若今天的月等于生日的月:
else:
# 若今天的日小于生日的日,年龄=今年的年-生日的年-1
if v_day_end<v_day_start:
age=v_year_end-v_year_start-1
# 若今天的日大于等于生日的日,年龄=今年的年-生日的年
else:
age=v_year_end-v_year_start
2、封装
def calculate_age(temp_data):
'''
Function: 根据身份证计算周岁年龄
Parameters: temp_data为身份证号
Return: 该身份证号周岁年龄
计算逻辑:
若今天计算周岁有以下几个特征:
1、若今天的月大于生日的月,年龄=今年的年-生日的年
2、若今天的月小于生日的月,年龄=今年的年-生日的年-1
3、若今天的月等于生日的月:
若今天的日小于生日的日,年龄=今年的年-生日的年-1
若今天的日大于等于生日的日,年龄=今年的年-生日的年
'''
v_start_date=temp_data[6:14]
now = datetime.datetime.now()
now = now.strftime('%Y%m%d')
v_year_end=datetime.datetime.strptime(now, '%Y%m%d').year
v_month_end=datetime.datetime.strptime(now, '%Y%m%d').month
v_day_end=datetime.datetime.strptime(now, '%Y%m%d').day
v_year_start=datetime.datetime.strptime(v_start_date, '%Y%m%d').year
v_month_start=datetime.datetime.strptime(v_start_date, '%Y%m%d').month
v_day_start=datetime.datetime.strptime(v_start_date, '%Y%m%d').day
#1、若今天的月大于生日的月,年龄=今年的年-生日的年
if v_month_end>v_month_start:
age=v_year_end-v_year_start
#2、若今天的月小于生日的月,年龄=今年的年-生日的年-1
elif v_month_end<v_month_start:
age=v_year_end-v_year_start-1
#3、若今天的月等于生日的月:
else:
# 若今天的日小于生日的日,年龄=今年的年-生日的年-1
if v_day_end<v_day_start:
age=v_year_end-v_year_start-1
# 若今天的日大于等于生日的日,年龄=今年的年-生日的年
else:
age=v_year_end-v_year_start
return age
3、调用
col_name='身份证号'
data=pd.DataFrame({col_name:['110221195404083625','110221195104073628','110109196404090678','110109195706010923','110109195501031210']})
data['age']=data[col_name].apply(lambda x:calculate_age(x))