Search code examples
pythondatetimetimedeltapython-polars

Python Polars: Elegant way to add a month to a date?


I need to carry out a very simple operation in Polars, but the documentation and examples I have been finding are super convoluted. I simply have a date, and I would like to create a range running from the first day in the following month until the first day of a month twelve months later.

I have a date:
date = 2023-01-15

I want to find these two dates:
range_start = 2023-02-01
range_end = 2024-02-01

How is this done in Polars?

In datetime in Python

from datetime import datetime
from dateutil import relativedelta
my_date = datetime.fromisoformat("2023-01-15")
start = my_date.replace(day=1) + relativedelta.relativedelta(months=1)
end = start + relativedelta.relativedelta(months=12)

Polars?

# The format of my date
import polars as pl
my_date_pl = pl.lit(datetime.fromisoformat("2023-01-15"))
????

Solution

  • You can use dt.offset_by

    For example

    pl.select(pl.lit(datetime.fromisoformat("2023-01-15")).dt.offset_by("1mo")).item()
    

    To avoid that error you can suffix "_saturating" to the offset like this...

    pl.select(pl.lit(datetime.fromisoformat("2023-01-31")).dt.offset_by("1mo_saturating")).item()
    

    It'll produce an error if the next month doesn't have the same date for example Jan 31 + 1 month will error.