python 自定義方法獲取最近幾個月的日期比如最近幾月的日期

def calDate(self, months): pass today = datetime。date。today()。strftime(“%Y-%m-%d”) cur_year = int(str(today)[0:4]) cur_month = int(str(today)[5:7]) # 最近一個月 if cur_month -1 == 0: pass year = cur_year -1 month = 12 else: year = cur_year month = cur_month -1 date = calendar。monthrange(year, month) # 最近 months 月數 if cur_month -months == 0: pass latest_year = cur_year -1 latest_month = 12 else: latest_year = cur_year latest_month = cur_month -months latest_date = calendar。monthrange(year, month) return (str(year)+‘-’+str(month)+‘-’+str(date[1]), str(latest_year)+‘-’+str(latest_month)+‘-’+‘01’)