Retrieve date from datetime column in polars
Question:
Currently when I try to retrieve date from a polars datetime column, I have to write sth. similar to:
df = pl.DataFrame({
'time': [dt.datetime.now()]
})
df = df.select([
pl.col("*"),
pl.col("time").apply(lambda x: x.date()).alias("date")
])
Is there a different way, something closer to:
pl.col("time").dt.date().alias("date")
Answers:
You can cast a Datetime
column to a Date
column:
import datetime
import polars as pl
df = pl.DataFrame({
'time': [datetime.datetime.now()]
})
df.with_column(
pl.col("time").cast(pl.Date)
)
shape: (1, 1)
┌────────────┐
│ time │
│ --- │
│ date │
╞════════════╡
│ 2022-08-02 │
└────────────┘
Since polars version 0.16.15 (released just a few days ago). The code in your question is actually valid.
pl.col("time").dt.date().alias("date")
This is the diff that made it possible. And it works both on pl.Series
and pl.Expr
(used in lazy data frames).
Currently when I try to retrieve date from a polars datetime column, I have to write sth. similar to:
df = pl.DataFrame({
'time': [dt.datetime.now()]
})
df = df.select([
pl.col("*"),
pl.col("time").apply(lambda x: x.date()).alias("date")
])
Is there a different way, something closer to:
pl.col("time").dt.date().alias("date")
You can cast a Datetime
column to a Date
column:
import datetime
import polars as pl
df = pl.DataFrame({
'time': [datetime.datetime.now()]
})
df.with_column(
pl.col("time").cast(pl.Date)
)
shape: (1, 1)
┌────────────┐
│ time │
│ --- │
│ date │
╞════════════╡
│ 2022-08-02 │
└────────────┘
Since polars version 0.16.15 (released just a few days ago). The code in your question is actually valid.
pl.col("time").dt.date().alias("date")
This is the diff that made it possible. And it works both on pl.Series
and pl.Expr
(used in lazy data frames).