python3 通过年月日获取准确的年龄

要做个防沉迷验证,需要精确判断0-8,8-16,16-18和18+的用户,单纯使用年份相减显得不太严谨

解决方案

def get_user_age(idcard):
    birth_date = datetime.datetime(year=int(idcard[6:14][:4]), month=int(idcard[6:14][4:6]), day=int(idcard[6:14][6:8]))
    now_time = datetime.datetime.now()
    age = now_time.year - birth_date.year
    if now_time.year > birth_date.year and (birth_date.month > now_time.month or (birth_date.month == now_time.month and birth_date.day > now_time.day)):
        # 如果今年未到生日那天,那么应该减去一岁,不然就算12月份的生日,到了1月也会算成一岁
        # now_time.year > birth_date.year 是为了规避现在是2022年,然后出生年份也是2022年的话,最后age会变成-1的问题
        age -= 1
    return age

USE

print(get_user_age('000000199505060000'))
# 返回27

“python3 通过年月日获取准确的年龄”的一个回复

发表评论

您的电子邮箱地址不会被公开。