Reputation: 540
I'd like to cast a column with the type datetype[ms]
to datetime[ns]
in polars. Is there a easy way to do this?
I think there's a problem with group_by_dynamic
when using datetime[ms]
and I'd like to test this
Upvotes: 3
Views: 6374
Reputation: 14670
You can use .dt.cast_time_unit()
s = pl.datetime_range(
pl.datetime(2021, 1, 1), pl.datetime(2021, 1, 2),
interval="3h", time_unit="ns", eager=True
)
s.dt.cast_time_unit("ms")
shape: (9,)
Series: '' [datetime[ms]]
[
2021-01-01 00:00:00
2021-01-01 03:00:00
2021-01-01 06:00:00
2021-01-01 09:00:00
2021-01-01 12:00:00
2021-01-01 15:00:00
2021-01-01 18:00:00
2021-01-01 21:00:00
2021-01-02 00:00:00
]
Upvotes: 9
Reputation: 1187
You can also use cast_time_unit
directly. It works more generally to convert datetime[x]
to datetime[y]
without you requiring to think about conversion factors.
For example:
df = pl.DataFrame(data = {
"date": pl.datetime_range(
pl.datetime(2021, 1, 1), pl.datetime(2021, 1, 2),
interval="3h", time_unit="ns", eager=True,
)}
)
df = df.with_columns(pl.col("date").dt.cast_time_unit("ms"))
Also produces the desired result
>>> print(df)
shape: (9, 1)
┌─────────────────────┐
│ date │
│ --- │
│ datetime[ms] │
╞═════════════════════╡
│ 2021-01-01 00:00:00 │
│ 2021-01-01 03:00:00 │
│ 2021-01-01 06:00:00 │
│ 2021-01-01 09:00:00 │
│ 2021-01-01 12:00:00 │
│ 2021-01-01 15:00:00 │
│ 2021-01-01 18:00:00 │
│ 2021-01-01 21:00:00 │
│ 2021-01-02 00:00:00 │
└─────────────────────┘
Upvotes: 2