'Python Polars Parse Date from Epoch

How does one convert a column of i64 epoch strings into dates in polars?

I've got a column of i64 representing seconds since epoch and I'd like to parse them into polars native datetimes.



Solution 1:[1]

Polars' Datetime is represented as unix epoch in either, nanoseconds, microseconds or milliseconds. So with that knowledge we can convert the seconds to milliseconds and cast to Datetime.

Finally we ensure polars uses the proper unit.

df = pl.DataFrame({
    "epoch_seconds": [1648457740, 1648457740 + 10]
})

MILLISECONDS_IN_SECOND = 1000;

df.select(
    (pl.col("epoch_seconds") * MILLISECONDS_IN_SECOND).cast(pl.Datetime).dt.with_time_unit("ms").alias("datetime")
)
shape: (2, 1)
???????????????????????
? datetime            ?
? ---                 ?
? datetime[ms]        ?
???????????????????????
? 2022-03-28 08:55:40 ?
???????????????????????
? 2022-03-28 08:55:50 ?
???????????????????????

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DataWiz