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)