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

Polars Adding Days to a date

I am using Polars in Python to try and add thirty days to a date
I run the code, get no errors but also get no new dates
Can anyone see my mistake?


import polars as pl

mydf = pl.DataFrame(
    {"start_date": ["2020-01-02", "2020-01-03", "2020-01-04"]})

mydf = mydf.with_column(
    pl.col("start_date").str.strptime(pl.Date, "%Y-%m-%d"),
    )

# Generate the days above and below
mydf = mydf.with_column(
    pl.col('start_date') + pl.duration(days=30).alias('date_plus_delta')
) 

mydf = mydf.with_column(
    pl.col('start_date') + pl.duration(days=-30).alias('date_minus_delta')
) 

print(mydf)

shape: (3, 1)
┌────────────┐
│ start_date │
│ ---        │
│ date       │
╞════════════╡
│ 2020-01-02 │
│ 2020-01-03 │
│ 2020-01-04 │
└────────────┘

Quick References

The Manual: https://pola-rs.github.io/polars-book/user-guide/howcani/data/timestamps.html

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

strftime formats: https://docs.rs/chrono/latest/chrono/format/strftime/index.html

SO Answer from a previous Post: How to add a duration to datetime in Python polars

>Solution :

You’re supposed to call .alias on the entire operation pl.col('start_date') + pl.duration(days=30). Instead you’re only alias-ing on pl.duration(days=30).

So the correct way would be:

import polars as pl

mydf = pl.DataFrame({"start_date": ["2020-01-02", "2020-01-03", "2020-01-04"]})
mydf = mydf.with_columns(pl.col("start_date").str.strptime(pl.Date, r"%Y-%m-%d"))

# Generate the days above and below
mydf = mydf.with_columns((pl.col('start_date') + pl.duration(days=30)).alias('date_plus_delta'))
mydf = mydf.with_columns((pl.col('start_date') - pl.duration(days=30)).alias('date_minus_delta'))

print(mydf)

Output

shape: (3, 3)
┌────────────┬─────────────────┬──────────────────┐
│ start_date ┆ date_plus_delta ┆ date_minus_delta │
│ ---        ┆ ---             ┆ ---              │
│ date       ┆ date            ┆ date             │
╞════════════╪═════════════════╪══════════════════╡
│ 2020-01-02 ┆ 2020-02-01      ┆ 2019-12-03       │
│ 2020-01-03 ┆ 2020-02-02      ┆ 2019-12-04       │
│ 2020-01-04 ┆ 2020-02-03      ┆ 2019-12-05       │
└────────────┴─────────────────┴──────────────────┘
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