python根据出生日期返回年龄的方法

本文实例讲述了python根据出生日期返回年龄的方法。分享给大家供大家参考。具体实现方法如下:

def calculateage(self, 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, days until %d: %d' % (age, age+1, 0) else: daysleft = nextyear - today return '%d, days until %d: %d' % (age, age+1, daysleft.days) except: return 'wrong date format'

使用方法如下:

print checkdate(‘2000.05.05’)

希望本文所述对大家的python程序设计有所帮助。

Posted in 未分类