本文實例講述了python根據(jù)出生日期獲得年齡的方法。分享給大家供大家參考。具體如下:
這段代碼可以根據(jù)用戶的出生日期獲得其年齡,born參數(shù)為date類型
1
2
3
4
5
6
7
8
9
10
11
12
|
def calculate_age(born): today = date.today() 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 birthday > today: return today.year - born.year - 1 else : return today.year - born.year |
希望本文所述對大家的Python程序設(shè)計有所幫助。