Get (year,month) for the last X months

后端 未结 7 716
死守一世寂寞
死守一世寂寞 2020-12-10 05:06

I got a very simple thing to to in python: I need a list of tuples (year,month) for the last x months starting (and including) from today. So, for x=10 and toda

7条回答
  •  死守一世寂寞
    2020-12-10 05:38

    Using relativedelta ...

    import datetime
    from dateutil.relativedelta import relativedelta
    
    def get_last_months(start_date, months):
        for i in range(months):
            yield (start_date.year,start_date.month)
            start_date += relativedelta(months = -1)
    
    >>> X = 10       
    >>> [i for i in get_last_months(datetime.datetime.today(), X)]
    >>> [(2013, 2), (2013, 1), (2012, 12), (2012, 11), (2012, 10), (2012, 9), (2012, 8), (2012, 7), (2012, 6), (2012, 5)]
    

提交回复
热议问题