You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Pandas迁移至Polars:如何用表达式高效判断夏令时?

用Polars原生表达式高效判断夏令时

可以利用Polars的dt.utc_offset()方法实现矢量化判断,完全替代低效的map_elements。核心逻辑是:夏令时会改变本地时间相对于UTC的偏移量,只要当前时间的UTC偏移与该时区的**标准偏移(非夏令时)**不一致,就说明处于夏令时。

实现步骤

  1. 从数据中提取该时区的标准UTC偏移(取所有时间点中最小的偏移值,以悉尼时区为例,非夏令时偏移为UTC+10小时,即36000秒);
  2. 通过对比每个时间点的UTC偏移与标准偏移,生成夏令时标识列。

完整代码

from datetime import datetime, timedelta
import numpy as np
import polars as pl

# 生成示例数据
df = pl.DataFrame({
    "timestamp": pl.datetime_range(
        datetime(2017, 1, 1),
        datetime(2018, 1, 1),
        timedelta(minutes=15),
        time_zone="Australia/Sydney",
        time_unit="ms", eager=True),
})
value = np.random.normal(0, 1, len(df))
df = df.with_columns([pl.Series(value).alias("value")])

# 计算该时区的标准UTC偏移(非夏令时)
standard_offset = df.select(pl.col("timestamp").dt.utc_offset().min()).item()

# 生成夏令时标识列
df = df.with_columns(
    pl.when(pl.col("timestamp").dt.utc_offset() != standard_offset)
    .then(1)
    .otherwise(0)
    .alias("dst")
)

优势说明

  • 完全基于Polars原生矢量化表达式,避免了map_elements的逐行处理开销,在大数据量下性能提升显著;
  • 无需硬编码时区偏移,逻辑通用,适配任何支持夏令时的时区。

内容的提问来源于stack exchange,提问作者David Waterworth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 11:07:54