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爲女性。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章