Generate list of months between interval in python

后端 未结 10 1176
庸人自扰
庸人自扰 2020-12-08 02:14

I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows:

date1 = \"2014-10-10\"  #         


        
10条回答
  •  Happy的楠姐
    2020-12-08 02:37

    I found a very succinct way to do this with Pandas, sharing in case it helps anybody:


    UPDATE: I've got it down to a one-liner with the help of this post :)

    pd.date_range('2014-10-10','2016-01-07', 
                  freq='MS').strftime("%Y-%b").tolist()
    

    OLD ANSWER:

    daterange = pd.date_range('2014-10-10','2016-01-07' , freq='1M') 
    daterange = daterange.union([daterange[-1] + 1])  
    daterange = [d.strftime('%y-%b') for d in daterange]
    

    The second line prevents the last date from getting clipped off the list.

提交回复
热议问题