python根据出生日期返回年龄

2022-04-29 00:00:00 返回 年龄 出生日期

python根据出生日期返回年龄,并计算离下一个生日还有多少天

"""
皮蛋编程(https://www.pidancode.com)
创建日期:2022/4/1
功能描述:python根据出生日期返回年龄
"""
import datetime

def CalculateAge(Date):
    '''Calculates the age and days until next birthday from the given birth date'''
    try:
        Date = Date.split('-')
        BirthDate = datetime.date(int(Date[0]), int(Date[1]), int(Date[2]))
        Today = datetime.date.today()
        if (Today.month > BirthDate.month):
            NextYear = datetime.date(Today.year + 1, BirthDate.month, BirthDate.day)
        elif (Today.month < BirthDate.month):
            NextYear = datetime.date(Today.year, Today.month + (BirthDate.month - Today.month), BirthDate.day)
        elif (Today.month == BirthDate.month):
            if (Today.day > BirthDate.day):
                NextYear = datetime.date(Today.year + 1, BirthDate.month, BirthDate.day)
            elif (Today.day < BirthDate.day):
                NextYear = datetime.date(Today.year, BirthDate.month, Today.day + (BirthDate.day - Today.day))
            elif (Today.day == BirthDate.day):
                NextYear = 0
        Age = Today.year - BirthDate.year
        if NextYear == 0:  # if today is the birthday
            return '%d岁, 离 %d岁还有 %d天' % (Age, Age + 1, 0)
        else:
            DaysLeft = NextYear - Today
            return '%d岁, 离 %d岁还有: %d天' % (Age, Age + 1, DaysLeft.days)
    except:
        return '日期输入格式不正确,格式如:2000-12-2'


print(CalculateAge('2001-02-18'))

输出结果:
21岁, 离 22岁还有: 323天

相关文章