python两个日期计算年龄

1. 按月份计算年龄

比如当前是2020.8月份,2019.8月份之前出生的都是1岁,8月份之后出生的是0岁,

def calculate_age(birth):
    birth_d = datetime.datetime.strptime(birth, "%Y-%m-%d")
    today_d = datetime.datetime.now()
    if today_d.month> birth_d.month:
        age = today_d.year - birth_d.year
    else:
        age = today_d.year - birth_d.year - 1
    return age

2. 按生日计算年龄

过了年龄就+1,没过年龄-1,注意判断条件

def calculate_age(birth):
    birth_d = datetime.datetime.strptime(birth, "%Y-%m-%d")
    today_d = datetime.datetime.now()
    birth_t = birth_d.replace(year=today_d.year)
    if today_d > birth_t:
        age = today_d.year - birth_d.year
    else:
        age = today_d.year - birth_d.year - 1
    return age
  1. 按年计算,虚岁
def calculate_age(birth):
    birth_d = datetime.datetime.strptime(birth, "%Y-%m-%d")
    today_d = datetime.datetime.now()
    age = today_d.year - birth_d.year
    return age

你可能感兴趣的:(小知识,python)