Python 月范围计算不需要';t返回预期结果
如果我将日期设置为以下日期:Python 月范围计算不需要';t返回预期结果,python,python-3.x,datetime,python-dateutil,relativedelta,Python,Python 3.x,Datetime,Python Dateutil,Relativedelta,如果我将日期设置为以下日期: from datetime import datetime from dateutil import relativedelta class count_month_range: 'Get the month range between 2 specified date based on the timezone' def __init__(self, start_date, end_date, timezone): self.sta
from datetime import datetime
from dateutil import relativedelta
class count_month_range:
'Get the month range between 2 specified date based on the timezone'
def __init__(self, start_date, end_date, timezone):
self.start_date = start_date
self.end_date = end_date
self.timezone = timezone
def count(self):
start_date = datetime.strptime(str(self.start_date), '%Y-%m-%dT%H:%M:%S'+self.timezone)
end_date = datetime.strptime(str(self.end_date), '%Y-%m-%dT%H:%M:%S'+self.timezone)
r = relativedelta.relativedelta(end_date, start_date)
print (r.months)
return r.months
month_range = count_month_range("2018-12-01T00:00:00Z", "2019-12-01T00:00:00Z", "Z")
test = month_range.count()
print(test)
它将返回以下意外结果:
0
0
我希望它返回12
我正在尝试获得月份范围
例如:2018-12-01到2019-10-31将给我10个月的结果
我有以下python test.py文件:
from datetime import datetime
from dateutil import relativedelta
class count_month_range:
'Get the month range between 2 specified date based on the timezone'
def __init__(self, start_date, end_date, timezone):
self.start_date = start_date
self.end_date = end_date
self.timezone = timezone
def count(self):
start_date = datetime.strptime(str(self.start_date), '%Y-%m-%dT%H:%M:%S'+self.timezone)
end_date = datetime.strptime(str(self.end_date), '%Y-%m-%dT%H:%M:%S'+self.timezone)
r = relativedelta.relativedelta(end_date, start_date)
print (r.months)
return r.months
month_range = count_month_range("2018-12-01T00:00:00Z", "2019-10-31T00:00:00Z", "Z")
test = month_range.count()
print(test)
当我运行test.py文件时,它将返回以下内容
10
10
这是预期的结果
如果2018-12-01至2019-10-31返回的10个月是正确的,我希望在输入时使用相同的正确计算:
2018-12-01至2019-12-01
每当我在“开始日期”和“结束日期”中输入同一个月时,无论年份不同,都会出现这种问题。
我应该怎么做才能使它按预期工作?
非常感谢你的帮助
提前感谢。当您使用提供的测试数据时,您会得到相对寿命(年=+1)。 因此,当您返回relativedelta对象时,需要将年份转换为月份,并与月份相加:
total_months = r.years * 12 + r.months
另一个例子。以下测试返回该值:relativedelta(年=+1,月=+1)
count_month_range("2018-11-01T00:00:00Z", "2019-12-01T00:00:00Z", "Z")