Get (year,month) for the last X months

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

    Or you can define a function to get the last month, and then print the months ( it's a bit rudimentary)

    def last_month(year_month):#format YYYY-MM
        aux = year_month.split('-')
        m = int(aux[1])
        y = int(aux[0])
    
        if m-1 == 0:
            return str(y-1)+"-12"
        else:
            return str(y)+"-"+str(m-1)
    
    def print_last_month(ran, year_month= str(datetime.datetime.today().year)+'-'+str(datetime.datetime.today().month)):
        i = 1 
        if ran != 10:
            print( last_month(year_month) )
            print_last_month(i+1, year_month= last_month(year_month))
    

提交回复
热议问题