from faker import Faker
import csv,datetime
from pathlib import Path
base_dir=Path.cwd()
data_dir=base_dir/'test_data'
faker=Faker(locale='zh-CN')
class GetIDCardInfo():
def __init__(self,tcardID):
self.tcardID = tcardID
self.birth_year = int(self.tcardID[6:10])
self.birth_month = int(self.tcardID[10:12])
self.birth_day = int(self.tcardID[12:14])
def get_birthday(self):
# 通过身份证取出生日,日期格式化输出,处理前导零的问题。':02d'
# birthday = "{0}-{1}-{2}".format(self.birth_year, self.birth_month, self.birth_day)
# return birthday
birthday = f"{self.birth_year}-{self.birth_month:02d}-{self.birth_day:02d}"
return birthday
def get_sex(self):
# 男:1,女:0
num = int(self.tcardID[16:17])
if num % 2 == 0:
return 0
else:
return 1
def get_age(self):
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
# # 调试段
# tcardID=faker.ssn(min_age=1, max_age=70)
# print(tcardID)
# tbirthday = GetIDCardInfo(tcardID).get_birthday()
# print(tbirthday)
# 构建数据并填写到csv文件,newline为另起一行去除空行
with open(data_dir/'testdata2.csv','w',encoding='utf-8',newline='') as f:
fwrite=csv.writer(f)
for i in range(1,11):
# 生成身份证
tcardID=faker.ssn(min_age=18, max_age=80)
print(tcardID)
# 拆解身份证获取生日
tbirthday = GetIDCardInfo(tcardID).get_birthday()
print(tbirthday)
# 获取性别
tsex = GetIDCardInfo(tcardID).get_sex()
# # 获取年龄
# tage = GetIDCardInfo(tcardID).get_age()
# 姓名
tname=faker.name()
# 电话
ttel=faker.phone_number()
# 地址
taddress=faker.address()
# 写入文件
fwrite.writerow([tname,tcardID,ttel,tbirthday,tsex,taddress])