输入身份证号码和日期算生日

# %%
from datetime import datetime

# %%
number = input("请输入一个身份证号码:")
now = input("请输入当前日期,例如2023-9-1:")

# %%
birth_date = number[6:14]
nowlist = now.split("-")

# %%
birth_datetime = datetime.strptime(birth_date, "%Y%m%d")
now_datetime = datetime.strptime(now, "%Y-%m-%d")

# %%
birth_year = birth_datetime.year
birth_month = birth_datetime.month
birth_day = birth_datetime.day
now_year = int(nowlist[0])  # 字符串转数字
now_month = int(nowlist[1])
now_day = int(nowlist[2])

# %%
if now_year == birth_year:
    age = 0
else:
    if birth_month > now_month or (birth_month==now_month and birth_day>now_day):
        age = now_year-birth_year-1
    else:
        age = now_year-birth_year

# %%
print("年龄为:",age,sep="")

你可能感兴趣的:(python)