Get (year,month) for the last X months

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

    If you create a function to do the date maths, it gets almost as nice as your original implementation:

    def next_month(this_year, this_month):
      if this_month == 0: 
        return (this_year - 1, 12)
      else:
        return (this_year, this_month - 1)
    
    this_month = datetime.date.today().month()
    this_year = datetime.date.today().year()
    for m in range(0, 10):
      yield (this_year, this_month)
      this_year, this_month = next_month(this_year, this_month)
    

提交回复
热议问题