def add_months(dt, count): _year = dt.year + (dt.month + count) / 12 _month = (dt.month + count) % 12 or 12 for i in range(0,4): try: return dt.replace(_year, _month, dt.day-i) except: continue