如何用Polars一次性将多列Unix时间戳转为UTC datetime?
批量将Polars DataFrame多列Unix时间戳转换为UTC datetime类型
解决方案代码
import polars as pl df = pl.from_repr(""" ┌─────┬────────────┬────────────┬────────────┐ │ id ┆ start_date ┆ end_date ┆ cancelable │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 ┆ bool │ ╞═════╪════════════╪════════════╪════════════╡ │ 1 ┆ 1566637530 ┆ 1566628686 ┆ true │ │ 2 ┆ 1561372720 ┆ 1561358079 ┆ true │ │ 3 ┆ 1561374780 ┆ 1561358135 ┆ false │ │ 4 ┆ 1558714718 ┆ 1556188225 ┆ false │ │ 5 ┆ 1558715044 ┆ 1558427697 ┆ true │ └─────┴────────────┴────────────┴────────────┘ """) columns_epoch_to_timestamp: list[str] = [ "start_date", "end_date", ] # 批量转换目标列为UTC datetime df = df.with_columns( pl.col(columns_epoch_to_timestamp).from_epoch(time_unit="s", time_zone="UTC") ) print(df)
代码说明
- 批量选中目标列:通过
pl.col(columns_epoch_to_timestamp)一次性选中所有需要转换的Unix时间戳列,Polars支持对列集合批量应用表达式操作。 - 时间戳转datetime:调用
.from_epoch()方法完成转换:time_unit="s":指定输入的时间戳是秒级(如果你的数据是毫秒/微秒级,对应修改为"ms"/"us")。time_zone="UTC":将转换后的datetime绑定到UTC时区,最终列类型为datetime[μs, UTC]。
- 单次调用完成转换:整个转换逻辑在一次
with_columns()调用中完成,无需逐个列单独处理,效率更高。
输出结果
shape: (5, 4) ┌─────┬──────────────────────────┬──────────────────────────┬────────────┐ │ id ┆ start_date ┆ end_date ┆ cancelable │ │ --- ┆ --- ┆ --- ┆ --- │ │ i64 ┆ datetime[μs, UTC] ┆ datetime[μs, UTC] ┆ bool │ ╞═════╪══════════════════════════╪══════════════════════════╪════════════╡ │ 1 ┆ 2019-08-24 09:05:30 UTC ┆ 2019-08-24 06:38:06 UTC ┆ true │ │ 2 ┆ 2019-06-24 10:38:40 UTC ┆ 2019-06-24 06:34:39 UTC ┆ true │ │ 3 ┆ 2019-06-24 11:13:00 UTC ┆ 2019-06-24 06:35:35 UTC ┆ false │ │ 4 ┆ 2019-05-24 16:18:38 UTC ┆ 2019-04-25 10:30:25 UTC ┆ false │ │ 5 ┆ 2019-05-24 16:24:04 UTC ┆ 2019-05-21 08:34:57 UTC ┆ true │ └─────┴──────────────────────────┴──────────────────────────┴────────────┘
内容的提问来源于stack exchange,提问作者Vega
相关产品推荐
相关产品推荐

