def _shift_month(date, months, day_option: DayOption = "start"):
    """Shift the date to a month start or end a given number of months away."""
    _ = attempt_import("cftime")

    has_year_zero = date.has_year_zero
    delta_year = (date.month + months) // 12
    month = (date.month + months) % 12

    if month == 0:
        month = 12
        delta_year = delta_year - 1

    if not has_year_zero:
        if date.year < 0 and date.year + delta_year >= 0:
            delta_year = delta_year + 1
        elif date.year > 0 and date.year + delta_year <= 0:
            delta_year = delta_year - 1

    year = date.year + delta_year

    # Silence warnings associated with generating dates with years < 1.
    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", message="this date/calendar/year zero")

        if day_option == "start":
            day = 1
        elif day_option == "end":
            reference = type(date)(year, month, 1, has_year_zero=has_year_zero)
            day = reference.daysinmonth
        else:
            raise ValueError(day_option)
        return date.replace(year=year, month=month, day=day)
Shift the date to a month start or end a given number of months away.
xarray/coding/cftime_offsets.py