Get (year,month) for the last X months

后端 未结 7 712
死守一世寂寞
死守一世寂寞 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:37

    Update: Adding a timedelta version anyway, as it looks prettier :)

    def get_years_months(start_date, months):
        for i in range(months):
            yield (start_date.year, start_date.month)
            start_date -= datetime.timedelta(days=calendar.monthrange(start_date.year, start_date.month)[1])
    

    You don't need to work with timedelta since you only need year and month, which is fixed.

    def get_years_months(my_date, num_months):
        cur_month = my_date.month
        cur_year = my_date.year
    
        result = []
        for i in range(num_months):
            if cur_month == 0:
                cur_month = 12
                cur_year -= 1
            result.append((cur_year, cur_month))
            cur_month -= 1
    
        return result
    
    if __name__ == "__main__":
        import datetime
        result = get_years_months(datetime.date.today(), 10)
        print result
    

提交回复
热议问题