15

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")

2 Answers 2

18

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 │
└────────────────────────────┴────────────┘
Sign up to request clarification or add additional context in comments.

1 Comment

I think this works if "time" is UTC but if it's localized I end up with i.e. 2024-04-01 00:00:00 AEDT (datetime[μs, Australia/Sydney]) being converted to 2024-03-31 (date). I would recomend using .dt.date() not .cast(pl.Date)
8

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).

2 Comments

what is stackoverflows procedure to update the question then, do I just add an edit on top?
I don't think you need to change anything :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.