Python:为什么不使用datetime.fromordinal进行年龄计算?
我对编程有点陌生,我想知道,是否可以使用方法Python:为什么不使用datetime.fromordinal进行年龄计算?,python,datetime,Python,Datetime,我对编程有点陌生,我想知道,是否可以使用方法datetime.fromordinal来计算年龄?我知道这不是为那个而做的,年龄和约会是不同的。 我环顾四周,没有发现有人建议使用这种方法。那么像这样的代码是否工作良好且可靠(我指的是在所有情况下)?我做了一些测试,结果还可以。是否建议使用这种方法 from datetime import date def calc_age(birthday=date(2000,2,29)): """returns the age as an intege
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
您的方法在大多数情况下可能有效,但我发现两个问题
date.fromordinal
用于返回实际日期,而不是相对的年数from datetime import date
def calc_age(birthday=date(2000,2,29)):
today = date.today()
age_on_this_year_birthday = today.year - birthday.year
this_year_birthday = date(today.year, birthday.month, birthday.day)
if today >= this_year_birthday:
return age_on_this_year_birthday
else:
return age_on_this_year_birthday - 1
您的方法在大多数情况下可能有效,但我发现两个问题
date.fromordinal
用于返回实际日期,而不是相对的年数from datetime import date
def calc_age(birthday=date(2000,2,29)):
today = date.today()
age_on_this_year_birthday = today.year - birthday.year
this_year_birthday = date(today.year, birthday.month, birthday.day)
if today >= this_year_birthday:
return age_on_this_year_birthday
else:
return age_on_this_year_birthday - 1
还有另一个模块,你可以使用它的日期好;它是箭头。你会怎么说
>>> import arrow
>>> arrow.get(2000,2,29).humanize()
'17 years ago'
在这种情况下,humanize将给定日期与当前日期和时间进行比较,但有一个附加参数允许用户与任何日期和时间进行比较
请参见还有另一个适合日期的模块;它是箭头。你会怎么说
>>> import arrow
>>> arrow.get(2000,2,29).humanize()
'17 years ago'
在这种情况下,humanize将给定日期与当前日期和时间进行比较,但有一个附加参数允许用户与任何日期和时间进行比较
看