[lang-ref] ( add_months ) ( python )

def test_add_months():
    def to_date(yyyymmdd):
        return datetime.datetime.strptime(yyyymmdd, r'%Y%m%d').date()

    def add_months(d, months):
        y = d.year
        m = d.month + months

        y += (m - 1) // 12
        m = (m - 1) % 12 + 1

        last = calendar.monthrange(y, m)[1]
        day = min(d.day, last)

        return d.replace(year=y, month=m, day=day)

    assert add_months(to_date('20250112'), 3) == to_date('20250412')
    assert add_months(to_date('20250131'), 1) == to_date('20250228')