Search code examples
pythondatetimepython-polarsstrftime

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'

Solution

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