Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to find the months between two dates

I have the need to be able to accurately find the months between two dates in python. I have a solution that works but its not very good (as in elegant) or fast.

dateRange = [datetime.strptime(dateRanges[0], "%Y-%m-%d"), datetime.strptime(dateRanges[1], "%Y-%m-%d")] months = []   tmpTime = dateRange[0] oneWeek = timedelta(weeks=1) tmpTime = tmpTime.replace(day=1) dateRange[0] = tmpTime dateRange[1] = dateRange[1].replace(day=1) lastMonth = tmpTime.month months.append(tmpTime) while tmpTime < dateRange[1]:     if lastMonth != 12:         while tmpTime.month <= lastMonth:             tmpTime += oneWeek         tmpTime = tmpTime.replace(day=1)         months.append(tmpTime)         lastMonth = tmpTime.month      else:         while tmpTime.month >= lastMonth:             tmpTime += oneWeek         tmpTime = tmpTime.replace(day=1)         months.append(tmpTime)         lastMonth = tmpTime.month 

So just to explain, what I'm doing here is taking the two dates and converting them from iso format into python datetime objects. Then I loop through adding a week to the start datetime object and check if the numerical value of the month is greater (unless the month is December then it checks if the date is less), If the value is greater I append it to the list of months and keep looping through until I get to my end date.

It works perfectly it just doesn't seem like a good way of doing it...

like image 269
Joshkunz Avatar asked Oct 28 '10 04:10

Joshkunz


People also ask

How do I find the difference in months between two dates in Excel?

Use the DATEDIF function when you want to calculate the difference between two dates. First put a start date in a cell, and an end date in another. Then type a formula like one of the following.

How do I calculate months between two dates in Excel without Datedif?

Another method to get the number of months between two specified dates is by using the YEARFRAC function. The YEARFRAC function will take a start date and end date as input arguments and it will give you the number of years that have passed during these two dates.


1 Answers

Start by defining some test cases, then you will see that the function is very simple and needs no loops

from datetime import datetime  def diff_month(d1, d2):     return (d1.year - d2.year) * 12 + d1.month - d2.month  assert diff_month(datetime(2010,10,1), datetime(2010,9,1)) == 1 assert diff_month(datetime(2010,10,1), datetime(2009,10,1)) == 12 assert diff_month(datetime(2010,10,1), datetime(2009,11,1)) == 11 assert diff_month(datetime(2010,10,1), datetime(2009,8,1)) == 14 

You should add some test cases to your question, as there are lots of potential corner cases to cover - there is more than one way to define the number of months between two dates.

like image 162
John La Rooy Avatar answered Sep 20 '22 20:09

John La Rooy