def add_months(sourcedate, months=0): """ 獲取指定月份幾個月以後或以前的月份及日期 :param source_date: 起始日期 :param months: 月份跨度 :return: 返回起始日期source_date與months相加以後的日期,格式爲datetime.date """ month = sourcedate.month - 1 + months print("month:",month) print("sourcedate.month:",sourcedate.month+months) year = sourcedate.year + month // 12 month = month % 12 + 1 day = min(sourcedate.day, calendar.monthrange(year,month)[1]) return datetime.date(year, month, day)
stackoverflow傳送門
python