Consider the following Polars dataframe:
df = pl.DataFrame({
'date': ['2022-01-01', '2022-02-01', '2022-03-01']
})
df.with_column(pl.col('date').str.strptime(pl.Date, fmt='%Y-%m').cast(pl.Datetime)).alias('year-month')
Currently the dataframe is:
| date |
|---|
| 2022-01-01 |
| 2022-02-01 |
| 2022-03-01 |
The desired output is:
| date | year-month |
|---|---|
| 2022-01-01 | 2022-01 |
| 2022-02-01 | 2022-02 |
| 2022-03-01 | 2022-03 |
I have tried:
df.with_column(pl.col('date').str.strptime(pl.Date, fmt='%Y-%m').cast(pl.Datetime)).alias('year-month')
I get:
SchemaError: invalid series dtype: expected Utf8, got datetime[ns]
Thanks so much!!!
You'll need to first parse it as
Date, and then format it according to your desired format:Note that once you format it as
%Y-%m, it'll no longer be ofDatedtype