import calendar
import datetime
def get_recent_month(dt, months):
# dt: datetime
# months: int
month = dt.month - 1 + months
year = dt.year + month //12
month = month % 12 + 1
day = min(dt.day, calendar.monthrange(year, month)[1])
return dt.replace(year=year, month=month, day=day)