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

Polars replace_time_zone函数报“时区中无该时间”错误的咨询

解决Polars中replace_time_zone的时区不存在错误

问题背景

测试数据代码:

import polars as pl
import pandas as pd
from datetime import date, time, datetime

df = pl.DataFrame(
    pl.datetime_range(
        start=date(2022, 1, 3),
        end=date(2022, 9, 30),
        interval="5m",
        time_unit="ns",
        time_zone="UTC",
        eager=True
    ).alias("UTC")
)

使用convert_time_zone可正常转换时区(底层时间戳不变,仅转换时区显示):

df.select(
    pl.col("UTC").dt.convert_time_zone(time_zone="America/New_York").alias("US")
)

输出结果:

shape: (77_761, 1)
┌────────────────────────────────┐
│ US                             │
│ ---                            │
│ datetime[ns, America/New_York] │
╞════════════════════════════════╡
│ 2022-01-02 19:00:00 EST        │
│ 2022-01-02 19:05:00 EST        │
│ 2022-01-02 19:10:00 EST        │
│ 2022-01-02 19:15:00 EST        │
│ 2022-01-02 19:20:00 EST        │
│ …                              │
│ 2022-09-29 19:40:00 EDT        │
│ 2022-09-29 19:45:00 EDT        │
│ 2022-09-29 19:50:00 EDT        │
│ 2022-09-29 19:55:00 EDT        │
│ 2022-09-29 20:00:00 EDT        │
└────────────────────────────────┘

但使用replace_time_zone时触发错误:

df.select(
   pl.col("UTC").dt.replace_time_zone(time_zone="America/New_York").alias("US")
)

错误信息:

ComputeError: datetime '2022-03-13 02:00:00' is non-existent in time zone 'America/New_York'. 
You may be able to use `non_existent='null'` to return `null` in this case.

错误原因

replace_time_zone的作用是直接给现有时间戳替换时区标签,不修改底层时间戳数值。而2022年3月13日纽约时区进入夏令时,凌晨2:00到2:59的时间被跳过(直接从1:59 EST跳到3:00 EDT),原UTC时间对应的纽约本地时间正好落在这个不存在的区间,因此触发冲突报错。

解决方案

通过replace_time_zone的non_existent参数指定不存在时间的处理方式:

1. 将不存在的时间设为Null

df.select(
    pl.col("UTC").dt.replace_time_zone(time_zone="America/New_York", non_existent="null").alias("US")
)

效果:所有对应纽约时区不存在的时间点会被替换为null。

2. 向前偏移到下一个存在的时间

df.select(
    pl.col("UTC").dt.replace_time_zone(time_zone="America/New_York", non_existent="shift-forward").alias("US")
)

效果:不存在的时间点会被自动偏移到夏令时切换后的第一个有效时间(比如原02:00会变成03:00)。

3. 向后偏移到上一个存在的时间

df.select(
    pl.col("UTC").dt.replace_time_zone(time_zone="America/New_York", non_existent="shift-backward").alias("US")
)

效果:不存在的时间点会被自动偏移到夏令时切换前的最后一个有效时间(比如原02:00会变成01:55)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 01:22:01