美文网首页
python3身份证验证

python3身份证验证

作者: qinbatista | 来源:发表于2020-09-27 17:40 被阅读0次

    import datetime

    class ChineseIDVerifyManager(object):

        def __init__(self,id):

            self.id = id

            self.is_correct_chinese_id = False

            self.is_correct_chinese_id = self.veriy_id_number(id)

            if self.is_correct_chinese_id:

                self.birth_year = int(self.id[6:10])

                self.birth_month = int(self.id[10:12])

                self.birth_day = int(self.id[12:14])

            else:

                print("[init]Failed id card")

        def get_birthday(self):

            if self.is_correct_chinese_id:

                """通过身份证号获取出生日期"""

                birthday = "{0}-{1}-{2}".format(self.birth_year, self.birth_month, self.birth_day)

                return birthday

        def get_sex(self):

            if self.is_correct_chinese_id:

                """男生:1 女生:2"""

                num = int(self.id[16:17])

                if num % 2 == 0:

                    return 2

                else:

                    return 1

        def get_age(self):

            """通过身份证号获取年龄"""

            if self.is_correct_chinese_id:

                now = (datetime.datetime.now() + datetime.timedelta(days=1))

                year = now.year

                month = now.month

                day = now.day

                if year == self.birth_year:

                    return 0

                else:

                    if self.birth_month > month or (self.birth_month == month and self.birth_day > day):

                        return year - self.birth_year - 1

                    else:

                        return year - self.birth_year

        def veriy_id_number(self,id_number):

            ten = ['X', 'x', 'Ⅹ']

            ID = ["10" if x in ten else x for x in id_number]    #将罗马数字Ⅹ和字母X替换为10

            W = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]

            Checkcode = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]

            sum = 0

            for i in range(17):

                sum = sum + int(ID[i]) * W[i]

            if Checkcode[sum % 11] == int(ID[17]):

                return True

            else:

                return False

    if __name__ == "__main__":

        id = '500102199404292351'

        birthday = ChineseIDVerifyManager(id).get_birthday() # 1995-09-25

        age = ChineseIDVerifyManager(id).get_age() # 23

        sex = ChineseIDVerifyManager(id).get_sex() # 23

        print("birthday="+str(birthday))

        print("age="+str(age))

        print("age="+str(sex))

    可以判断你的身份证是否合理,然后获取生日,年龄,性别

    相关文章

      网友评论

          本文标题:python3身份证验证

          本文链接:https://www.haomeiwen.com/subject/rjyluktx.html