Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:为什么不使用datetime.fromordinal进行年龄计算?_Python_Datetime - Fatal编程技术网

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
    用于返回实际日期,而不是相对的年数
  • 并非每四年都是闰年(例如1900年不是)
  • 更好的方法可能是减去年份,并考虑生日是否已过,因此将leapyear逻辑留给datetime处理

    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
    用于返回实际日期,而不是相对的年数
  • 并非每四年都是闰年(例如1900年不是)
  • 更好的方法可能是减去年份,并考虑生日是否已过,因此将leapyear逻辑留给datetime处理

    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将给定日期与当前日期和时间进行比较,但有一个附加参数允许用户与任何日期和时间进行比较