根據身份證年齡計算
阿新 • • 發佈:2019-01-09
年齡計算
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')