Search code examples
pythonpython-3.xdatetimepython-dateutilrelativedelta

Month Range Calculation Doesn't Return Expected Result


If I set the date to following:

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)

It will return unexpected result as follow:

0
0

I expect it return 12

I am trying to get the month range.

For example: 2018-12-01 until 2019-10-31 will give me result of 10 month.

I have the following python test.py file:

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)

It will return the following when I run test.py file

10
10

And that is the expected result.

If 2018-12-01 until 2019-10-31 returns 10 months which is correct, I expect the same correct calculation when entering: 2018-12-01 until 2019-12-01.

This kind of problem happens whenever I input the same month in start_date and end_date regardless the different year. What should I do to make it work as expected? Your help is very much appreciated.

Thanks in advance.


Solution

  • When you use the test data provided you get relativedelta(years=+1). Therefore when you are returning the relativedelta object you need to convert the years to months and sum it with the months:

    total_months = r.years * 12 + r.months
    

    Another example. The following test returns this: relativedelta(years=+1, months=+1)

    count_month_range("2018-11-01T00:00:00Z", "2019-12-01T00:00:00Z", "Z")