def get_age_from_idcard(idcard, applytime):
    """根据申请时间计算年龄,精确到日"""
    if len(idcard) == 18:
        birth_year = int(idcard[6:10])
        birth_month = idcard[10:12]
        birth_day = idcard[12:14]
    else:
        birth_year = int('19' + idcard[6:8])
        birth_month = idcard[8:10]
        birth_day = idcard[10:12]

    apply_date = date.fromtimestamp(applytime)

    year_diff = apply_date.year - birth_year

    apply_month_day = apply_date.strftime("%Y%m%d")[4:]
    birth_month_day = f"{birth_month}{birth_day}"

    if apply_month_day >= birth_month_day:
        return year_diff
    return year_diff - 1

UT

def test_get_age_from_idcard_when_one_age():
    applydate = 983289600  # 2001-2-28
    assert utils.get_age_from_idcard('130683200002293036', applydate) == 0


def test_get_age_from_idcard_when_one_age_when_normal_month():
    applydate = 1572537600  # 2019-11-01
    assert utils.get_age_from_idcard('130683201810313036', applydate) == 1


def test_get_age_from_idcard_when_zero_age_by_same_year():
    applydate = 951840000  # 2000-03-01
    assert utils.get_age_from_idcard('130683200002293036', applydate) == 0


def test_get_age_from_idcard_when_zero_age_by_same_month():
    applydate = 981648000  # 2001-02-09
    assert utils.get_age_from_idcard('130683200002293036', applydate) == 0


def test_get_age_from_idcard_when_birthday():
    applydate = 982598400  # 2001-02-20
    assert utils.get_age_from_idcard('130683200002203036', applydate) == 1


def test_get_age_from_id_card_when_id_card_short():
    applydate = 951753600  # 2000-02-29
    assert utils.get_age_from_idcard('1306830002293036', applydate) == 100
12-24 15:07