我有點新來編程,我想知道,是否有可能使用方法datetime.fromordinal
來計算年齡?我知道那不是爲了這個,而且年齡和約會之間有一個不同。 我環顧四周,並沒有發現任何人提出這種方法。那麼像這樣的代碼能夠正常工作並且可靠嗎(對於所有情況我的意思)?我跑了很少的測試,結果還可以。建議使用這種方法嗎?Python:爲什麼不使用datetime.fromordinal計算年齡?
from datetime import date
def calc_age(birthday=date(2000,2,29)):
"""returns the age as an integer value, given the birthday as a datetime.date object"""
today=date.today()
days=(today-birthday).days
if (birthday.year%4):
days-=364
else:
days-=365
return date.fromordinal(days).year