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
df = pl.DataFrame(
{"start_date": ["2020-01-02", "2020-01-03", "2020-01-04"]})
df = df.with_columns(
pl.col("start_date").str.to_date()
)
# Generate the days above and below
df = df.with_columns(
pl.col("start_date") + pl.duration(days=30).alias("date_plus_delta")
)
df = df.with_columns(
pl.col("start_date") + pl.duration(days=-30).alias("date_minus_delta")
)
print(df)
shape: (3, 1)
┌────────────┐
│ start_date │
│ --- │
│ date │
╞════════════╡
│ 2020-01-02 │
│ 2020-01-03 │
│ 2020-01-04 │
└────────────┘
Quick References
The Manual: https://docs.pola.rs/user-guide/transformations/time-series/parsing/
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
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
df = pl.DataFrame({"start_date": ["2020-01-02", "2020-01-03", "2020-01-04"]})
df = df.with_columns(pl.col("start_date").str.to_date())
# Generate the days above and below
df = df.with_columns((pl.col("start_date") + pl.duration(days=30)).alias("date_plus_delta"))
df = df.with_columns((pl.col("start_date") - pl.duration(days=30)).alias("date_minus_delta"))
print(df)
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 │
└────────────┴─────────────────┴──────────────────┘