Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format datetime in polars

I have a polars dataframe that contains a datetime column. I want to convert this column to strings in the format %Y%m. For example, all dates in January 2024 should be converted to "202401".

from datetime import datetime

import polars as pl


data = {
    "ID" : [1,2,3],
    "dates" : [datetime(2024,1,2),datetime(2024,1,3),datetime(2024,1,4)],
}

df = pl.DataFrame(data)

I have tried using strftime. However, the following AttributeError is raised.

AttributeError: 'Expr' object has no attribute 'strftime'
like image 836
Simon Avatar asked Jul 27 '26 01:07

Simon


1 Answers

Note that pl.Expr.dt.strftime is available under the pl.Expr.dt namespace. Hence, it is called on the dt attribute of an expression and not the expression directly.

df.with_columns(
    pl.col("dates").dt.strftime("%Y%m")
)
shape: (3, 2)
┌─────┬────────┐
│ ID  ┆ dates  │
│ --- ┆ ---    │
│ i64 ┆ str    │
╞═════╪════════╡
│ 1   ┆ 202401 │
│ 2   ┆ 202401 │
│ 3   ┆ 202401 │
└─────┴────────┘
like image 133
Hericks Avatar answered Jul 28 '26 20:07

Hericks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!