python身份证年龄计算_用python计算年龄

您也可以这样使用日期时间库。这将计算以年为单位的年龄,并删除由于月和日属性而返回错误年龄的逻辑错误

就好像1999年7月31日出生的人到2017年7月30日才17岁

下面是代码:import datetime

#asking the user to input their birthdate

birthDate = input("Enter your birth date (dd/mm/yyyy)\n>>> ")

birthDate = datetime.datetime.strptime(birthDate, "%d/%m/%Y").date()

print("Your birthday is on "+ birthDate.strftime("%d") + " of " + birthDate.strftime("%B, %Y"))

currentDate = datetime.datetime.today().date()

#some calculations here

age = currentDate.year - birthDate.year

monthVeri = currentDate.month - birthDate.month

dateVeri = currentDate.day - birthDate.day

#Type conversion here

age = int(age)

monthVeri = int(monthVeri)

dateVeri = int(dateVeri)

# some decisions

if monthVeri < 0 :

age = age-1

elif dateVeri < 0 and monthVeri == 0:

age = age-1

#lets print the age now

print("Your age is {0:d}".format(age))

你可能感兴趣的:(python身份证年龄计算)