I want to generate a python list containing all months occurring between two dates, which is separated by year in array as follow:
startdate = "2014-10-10" # input start date
enddate = "2016-01-07" # input end date
month_list = [['Oct-14', 'Nov-14', 'Dec-14'], ['Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15', 'Jul-15', 'Aug-15', 'Sep-15', 'Oct-15', 'Nov-15', 'Dec-15'], ['Jan-16']] # output
i tried this but it display only two year interval in array
import calendar
from datetime import *
startdate = datetime.strptime("2015-09-10", "%Y-%m-%d")
enddate = datetime.strptime("2016-5-15", "%Y-%m-%d")
month_str = calendar.month_name
curryear = startdate.year
months = []
yearss=[]
temp=[]
while startdate < enddate:
month = startdate.month
year = startdate.year
day = startdate.day
mon_str = month_str[month][0:3]
next_month = month + 1 if month != 12 else 1
if curryear == year:
months.append("{0}-{1}".format(mon_str, str(year)[-2:]))
startdate = startdate.replace(month=next_month, year=year)
next_year = year+1 if next_month==1 else year
if curryear != next_year:
startdate = startdate.replace(month=next_month, year=next_year)
temp.append("{0}-{1}".format(mon_str, str(next_year)[-2:]))
months.append(temp)
print(months)
Output: ['Sep-15', 'Oct-15', 'Nov-15', 'Dec-15', ['Dec-16', 'Jan-16', 'Feb-16', 'Mar-16', 'Apr-16', 'May-16']]