Search code examples
pythondataframepython-polars

Retrieve date from datetime column in polars


Currently when I try to retrieve date from a polars datetime column, I have to write something similar to:

import polars as pl
import datetime as dt

df = pl.DataFrame({
    'time': [dt.datetime.now()]
})

df = df.with_columns(
    pl.col("time").map_elements(lambda x: x.date()).alias("date")
)
shape: (1, 2)
┌────────────────────────────┬────────────┐
│ time                       ┆ date       │
│ ---                        ┆ ---        │
│ datetime[μs]               ┆ date       │
╞════════════════════════════╪════════════╡
│ 2024-07-20 11:41:04.265539 ┆ 2024-07-20 │
└────────────────────────────┴────────────┘

Is there a different way, something closer to:

pl.col("time").dt.date().alias("date")

Solution

  • You can use .dt.date()

    import datetime
    import polars as pl
    
    df = pl.DataFrame({
        "time": [datetime.datetime.now()]
    })
    
    df.with_columns(
        pl.col("time").dt.date().alias("date")
    )
    
    shape: (1, 2)
    ┌────────────────────────────┬────────────┐
    │ time                       ┆ date       │
    │ ---                        ┆ ---        │
    │ datetime[μs]               ┆ date       │
    ╞════════════════════════════╪════════════╡
    │ 2024-07-21 16:17:41.489579 ┆ 2024-07-21 │
    └────────────────────────────┴────────────┘