Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading