Home > Enterprise >  Polars Adding Days to a date
Polars Adding Days to a date

Time:02-01

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

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

CodePudding user response:

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       │
└────────────┴─────────────────┴──────────────────┘
  • Related