根据 dateutil.relativedelta 大于指定时间量的比较向日期添加月份

Adding months to a date based on a comparison where dateutil.relativedelta is greater than a specified amount of time

我的目标是根据 start_dateend_date 之间的时间段长度向 start_date 添加指定的月数。超过10年的,加3个月,否则加1个月。计算必须精确,并且应该能够考虑给定月份以及闰年的具体天数。我试图通过像这样使用 dateutil.relativedelta 来完成此操作:

from dateutil.relativedelta import relativedelta
from dateutil import parser

# Extract date from string
start_date = parser.parse("2050-11-01")
end_date = parser.parse("1980-11-01")

# Calculate difference
delta = relativedelta(start_date, end_date)
print(delta)

if delta > relativedelta(years=+10):
    new_end_date = start_date + relativedelta(months=3)
else:
   new_end_date = start_date + relativedelta(months=1)

print(new_end_date)

但是,这会产生以下输出:

relativedelta(years=+70)
TypeError: '>' not supported between instances of 'relativedelta' and 'relativedelta'

正在搜索 SO made it clear 上的错误,没有简单的方法可以比较 dateutil.relativedelta。有人知道我的用例的解决方法吗?

这是我的建议:

  • 设置您要测试的(相对)时期(10 年)
  • 将其添加到最早的输入日期
  • 检查新日期是否早于最新输入的日期

这样,您仍然可以获得 relativedelta 的相对性,但您会得到两个难以比较的日期:

from dateutil.relativedelta import relativedelta
from dateutil import parser

# Extract date from string
start_date = parser.parse("2050-11-01")
end_date = parser.parse("1980-11-01")

# Set the size of the period
period = relativedelta(years=10)

# Test if adding the period to the earliest date makes it surpass the latest date
if min(start_date, end_date) + period <= max(start_date, end_date):
    new_end_date = start_date + relativedelta(months=3)
else:
   new_end_date = start_date + relativedelta(months=1)

print(new_end_date)
# 2051-02-01 00:00:00

在这种情况下,开始和结束并不意味着更早和更晚,所以你必须做minmax操作。