Get python datetime from polars datetime

Question:

How do I get the python timestamp from the polars datetime object (which is a polars Expression)?

import polars as pl
pl_timestamp = pl.datetime(year=2020, month=6, day=5).dt.with_time_zone("UTC")
py_timestamp = ... 
Asked By: user20081698

||

Answers:

You can use polars.select to run Polars Expressions without a context.

pl.select(pl_timestamp)
shape: (1, 1)
┌─────────────────────────┐
│ datetime                │
│ ---                     │
│ datetime[μs, UTC]       │
╞═════════════════════════╡
│ 2020-06-05 00:00:00 UTC │
└─────────────────────────┘

From here, you can use indexing to convert to a Python object.

pl.select(pl_timestamp)[0, 0]
>>> pl.select(pl_timestamp)[0, 0]
datetime.datetime(2020, 6, 5, 0, 0)

Edit

The timezone information is maintained. For example:

pl_timestamp = pl.datetime(year=2020, month=6, day=5).dt.replace_time_zone("Europe/London")

pl.select(pl_timestamp)[0, 0]
>>> pl.select(pl_timestamp)[0, 0]
datetime.datetime(2020, 6, 5, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/London'))
Answered By: user18559875
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.