计算两个日期之间的年数,但以标准方式四舍五入

时间:2018-09-12 08:39:55

标签: python

我想获取两个日期之间的舍入年数。 relativedelta的{​​{1}}属性几乎可以做到这一点,但是由于它提供了不同的用例,因此总是舍入而不是使用标准舍入规则:

years

此输出from datetime import datetime, date from dateutil.relativedelta import relativedelta almost_one_year_ago = date.today() - relativedelta(years=1) + relativedelta(days=1) print(relativedelta(date.today(), almost_one_year_ago).years) ,我想要0

是否有一种很好的方法可以按照标准舍入规则将年数获取为整数?例如:如果小于0.5年,则向下舍入;如果大于或等于0.5,则向上舍入?

3 个答案:

答案 0 :(得分:2)

我找到了与leap年兼容的解决方案。它仍然没有我想要的干净,但是可以完成工作:

from datetime import datetime, date
from dateutil.relativedelta import relativedelta

def how_many_years_ago(input_date):
    difference = relativedelta(date.today(), input_date)
    result = difference.years

    # Round up if closer to the next year than the previous
    if difference.months >= 6:
        result += 1

    return result

# Exactly 1 year ago, should output 1
print(how_many_years_ago(date.today() - relativedelta(years=1)))

# Almost 1 year ago, should round up to 1
print(how_many_years_ago(date.today() - relativedelta(years=1) + relativedelta(days=1)))

# Too far removed from 35 years, should round down to 34
print(how_many_years_ago(date.today() - relativedelta(years=35) + relativedelta(months=8)))

# Almost 38 years ago, should round up to 38
print(how_many_years_ago(date.today() - relativedelta(years=38) + relativedelta(months=4)))

如果我不忽略某些警告(例如like年),则此实现可以解决我的问题。

答案 1 :(得分:1)

您可以计算天数差异,将其除以365,然后将其四舍五入:

print(round((date.today() - almost_one_year_ago).days/365))

考虑leap年的另一种方法:

from datetime import datetime, date
from dateutil.relativedelta import relativedelta

target_date = date.today() - relativedelta(years=1) + relativedelta(days=1)

year_cnt = 0
one_year_ago = date.today() - relativedelta(years=1)
while ( target_date < one_year_ago ):
    year_cnt += 1 # because it's a full year
    one_year_ago -= relativedelta(years=1)

half_year_ago = one_year_ago + relativedelta(months=6)
if ( target_date <= half_year_ago ):
    year_cnt += 1 # because it's greater or equal a half year (>= 0.5)

print(year_cnt)

我只计算所有年份,然后检查剩余时间是否超过半年。

答案 2 :(得分:1)

您可以使用days属性来计算年份,而不是使用years属性。这样,您就可以控制它的舍入方式