Format datetime in polars
Asked Answered
C

2

7

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'
Codeclination answered 6/8 at 21:9 Comment(0)
F
5

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 │
└─────┴────────┘
Fellowman answered 6/8 at 21:44 Comment(0)
O
5

you can use strftime like this:

df = df.with_columns(pl.col("dates").dt.strftime("%Y%m"))

print(df)
┌─────┬────────┐
│ ID  ┆ dates  │
│ --- ┆ ---    │
│ i64 ┆ str    │
╞═════╪════════╡
│ 1   ┆ 202401 │
│ 2   ┆ 202401 │
│ 3   ┆ 202401 │
└─────┴────────┘
Osteogenesis answered 6/8 at 21:17 Comment(0)
F
5

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 │
└─────┴────────┘
Fellowman answered 6/8 at 21:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.