根据身份证号计算周岁年龄

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))

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值