首页 > 编程语言 >python解析身份证获取年龄、出生日期、性别

python解析身份证获取年龄、出生日期、性别

时间:2023-03-26 21:01:41浏览次数:33  
标签:python int birthday today year 出生日期 解析 id card

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

标签:python,int,birthday,today,year,出生日期,解析,id,card
From: https://www.cnblogs.com/1314520xh/p/17259528.html

相关文章

  • 关于python编程中try...except的嵌套使用说明及注意事项
    今天笔者在写一个脚本时,情况比较复杂,在脚本中使用了try...except的嵌套,遇到了一些与预期不一样的结果于是笔者又研究了一下,try...except的嵌套使用,首先有一点是肯定的,那......
  • Python2.X和Python3.X版本有哪些主要的区别
    1.print函数在Python2中,print语句是关键字而不是函数,其语法如下:print"Hello,World!"在Python3中,print是一个函数,需要使用小括号来包裹print参数。如下:print("Hell......
  • 用Python解决Excel问题的最佳姿势
    「问题说明」这次要处理的excel有两个sheet,要根据其中一个sheet的数据来计算另外一个sheet的值。造成问题的点在于,要计算值的sheet里不仅仅有数值,还有公式。我们来看一下:如......
  • Centos7安装Python3.7
    说明:全部操作都在root用户下执行,python3.7安装在/root/python3目录下1.安装编译相关工具yum-ygroupinstall"Developmenttools"yum-yinstallzlib-develbzip2-dev......
  • python进制转换
    1. python中可以使用内置函数进行进制间的转换.bin(): 其他进制转换为二进制oct(): 其他进制转换为八进制int(): 其他进制转换为十进制he......
  • python中sorted排序
     key是自定义函数reverse=False,升序(默认)reverse=True,倒序#不区分大小写排序sorted(['bob','aBout','ZOO','Credit'],key=str.lower)#按绝对值排序sorted([36,5,-12......
  • python-concurrent
    python-concurrent概述__all__=('FIRST_COMPLETED','FIRST_EXCEPTION','ALL_COMPLETED','CancelledError','TimeoutError','BrokenExec......
  • python-threading
    python-threading目录python-threadingthreadingThread创建线程Thread方法属性守护线程线程锁Lockthreading.Lockthreading.RLock事件对象EventConditionTimerimportthr......
  • 浅析Nginx文件解析漏洞
    浅析Nginx文件解析漏洞本文章将从五个维度对Nginx文件解析漏洞进行剖析——原理、危害、检测、防御、复现1、原理​ Nginx文件解析漏洞的产生原因是由于Nginx配置文件de......
  • 关于python中的OSError报错问题
    Traceback(mostrecentcalllast): File"main.py",line1,in<module>   fromtrainerimportTrainer File"/home/visionx/mt/qg/paragraph_nqg_max_point_......