根据身份证年龄计算

版权声明:本文为博主自我学习原创文章,欢迎转载,转载请注明出处。 https://blog.csdn.net/Jack_kun/article/details/82988997

年龄计算

def calculate_age(input_born):
    '''
    : input_born: string, len=8
    '''
    import datetime

    y_born = input_born[0:4]
    m_born = input_born[4:6]
    d_born = input_born[6:8]
    
    born = datetime.date(int(y_born), int(m_born), int(d_born))
    today = datetime.date(2018,5,10)
    
    born_days = born - datetime.date(born.year-1, 12, 31)  #减去上一年最后一天,可得解
    target_days = today - datetime.date(today.year-1, 12, 31)
    sub_days = target_days - born_days
    sub_days = sub_days.days
    
#     try:
#         birthday = born.replace(year=today.year)
#     except ValueError:
#         # raised when birth date is February 29 
#         # and the current year is not a leap year
#         birthday = born.replace(year=today.year, day=born.day-1)
        
    if today > born:
        years = today.year-born.year
        if sub_days >= 0:
            if sub_days>=0 and sub_days<183:
                return years
            else:
                # sub_days in range(183,366,1):
                return years+1
        
        else:
            sub_days = abs(sub_days)
            if sub_days>=0 and sub_days<183:
                return years
            else:
                return years+1
    else:
        print('error_date')
        

猜你喜欢

转载自blog.csdn.net/Jack_kun/article/details/82988997