4

I need to implement the code which will help me to get the list of months between two dates.

I already have the code which will give the month delta , That is the number of months.

Actually, I need the way to achieve getting the list of months between two dates.

Here it is code for getting month delta.

import calendar
import datetime

def calculate_monthdelta(date1, date2):
    def is_last_day_of_the_month(date):
        days_in_month = calendar.monthrange(date.year, date.month)[1]
        return date.day == days_in_month
    imaginary_day_2 = 31 if is_last_day_of_the_month(date2) else date2.day
    monthdelta = (
        (date2.month - date1.month) +
        (date2.year - date1.year) * 12 +
        (-1 if date1.day > imaginary_day_2 else 0)
        )
    print monthdelta
    return monthdelta

date2 = datetime.datetime.today()
date1 = date2.replace(month=01)

calculate_monthdelta(date1, date2)

Now I need the way to get the list of months between the same.

Any help is appreciated If there is any way to get the list of months between two dates.

Note: Please suggest any idea (If available) apart from the code I have used here.

Sparky
  • 91
  • 1
  • 8

4 Answers4

13

try this

import datetime
import time
from dateutil.rrule import rrule, MONTHLY
months = [dt.strftime("%m") for dt in rrule(MONTHLY, dtstart=date1, until=date2)]
print months
cheng chen
  • 469
  • 4
  • 6
0
from datetime import datetime,timedelta
import time
d = date1
delta = timedelta(months=1)
while d <= date2:
    print d.strftime("%m")
    d += delta
cheng chen
  • 469
  • 4
  • 6
-1

Change your print statement to:
print calendar.month_name[:monthdelta]

shivsn
  • 6,820
  • 24
  • 33
NNNN
  • 1
  • 2
-1

Because I don't know your desired output I can't format mine, but this returns an integer of the total number of months between two dates.

def calculate_monthdelta(date1, date2):
    print abs(date1.year - date2.year) * 12 + abs(date1.month - date2.month)
TheLazyScripter
  • 2,426
  • 1
  • 9
  • 19