需求:想获取当前月的前n个月是几月
假设本月是2018年11月,那么上个月就是2018年10月,r如果月差n=2,那么月份就是2018年9月,n是可变的。
可能有人会说,用 datetime.replace 方法将 month-1 就好了,咋看起来没问题,实际上这是有 bug 的,因为month 的范围只能是 1-12
所以本人选择以递归的方式去解决该问题
def get_month_time(today_time, month):
today = today_time.replace(day=1)
before_time = today - datetime.timedelta(days=1)
if month <= 1:
return before_time
else:
return get_month_time(before_time, month - 1)
if __name__ == '__main__':
today_time = datetime.datetime.now()
print get_month_time(today_time, 11).month
即可完美的解决此问题