如果我将日期设置为以下:
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。
每当我在 start_date 和 end_date 中输入相同的月份时,就会发生这种问题,而不管不同的年份。我应该怎么做才能使其按预期工作?非常感激您的帮忙。
提前致谢。