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

Pandas .floor()对无歧义时间戳抛出AmbiguousTimeError的原因及解决方案咨询

Pandas .floor()对无歧义时间戳抛出AmbiguousTimeError的原因及解决方案咨询

我最近碰到个特别困惑的问题:明明用的是绝对无歧义的epoch时间戳,调用Pandas的.floor()方法时却抛出了AmbiguousTimeError,想跟大家请教下背后的原因,以及更优的解决方案。

问题重现

先贴一下出错的代码:

import pandas as pd
import pytz

def round_in_tz(epoch_sec: int, tz_name: str, freq_spec: str):
    """Round the given epoch timestamp to the nearest pandas time frequency spec in the given timezone."""
    return pd.to_datetime(epoch_sec, unit='s', utc=True).tz_convert(tz_name).floor(freq_spec)

# 这个调用正常返回结果
print(round_in_tz(1730610000, "US/Eastern", freq_spec="86400s"))  
# 这个调用直接报错:pytz.exceptions.AmbiguousTimeError: Cannot infer dst time from 2024-11-03 01:00:00, try using the 'ambiguous' argument
print(round_in_tz(1730610000, "US/Eastern", freq_spec="300s"))  

我的核心疑问

  1. 这里真的存在歧义吗?我清楚DST时区会有时间重叠的问题,但epoch时间戳本身是绝对唯一的时间点啊,这会不会是Pandas的bug?
  2. 有没有更优雅的改写方式?我自己凑了一个临时解决方案,但不确定是不是最优的:
def round_in_tz(epoch_sec: int, tz_name: str, freq_spec: str):
    """Round the given epoch timestamp to the nearest pandas time frequency spec in the given timezone."""
    t = pd.to_datetime(epoch_sec, unit='s', utc=True).tz_convert(tz_name)
    is_dst = bool(t.timetuple().tm_isdst)
    return t.floor(freq_spec, ambiguous=is_dst)

补充说明:我不能用.floor(freq_spec).tz_convert(tz_name)的写法,因为这样会改变freq_spec="86400s"时的行为——我想要的是美国东部时间的午夜,而不是UTC午夜转换到东部时间的时刻。

我之前看过不少关于DST歧义的问题,但那些都是解析字符串时间的场景(比如解析DST回退时段重复出现的时间字符串),但这次我用的是明确的epoch时间戳,实在想不通为什么会触发歧义错误。


备注:内容来源于stack exchange,提问作者tba

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 16:07:59