python解析身份证获取年龄、出生日期、性别
import re import datetime
def parse_id_card(id_card): # 获取身份证号中的出生年月日和性别和年龄 birthday_pattern = re.compile(r'\d{6}(\d{4})(\d{2})(\d{2})\d{3}[X\d]') match = birthday_pattern.match(id_card) if not match: return None year, month, day = match.groups() gender = int(id_card[-2]) % 2 == 1 # 1为男性,0为女性 # 计算年龄 birthday = datetime.date(int(year), int(month), int(day)) today = datetime.date.today() age = today.year - birthday.year - ((today.month, today.day) < (birthday.month, birthday.day)) return {'birthday': str(birthday), 'age': age, 'gender': 'male' if gender else 'female'}
#调用方式
parse_id_card('340827199209013412')
通过正则表达式解析身份证号码中的出生年月日,然后通过计算当前日期和出生日期之间的年差、月差和日差来计算年龄。同时,根据身份证号码的倒数第二位数字来判断性别,1为男性,0为女性。
心有猛虎,细嗅蔷薇