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

Pandas中基于超界Windows纪元的时间值转换为datetime的方法问询

超界纪元时间值转Pandas Datetime的解决方案

方法1:使用标准库datetime中转(逻辑最直观)

Python原生datetime类型支持的时间范围远大于Pandas Timestamp的限制,可先完成纪元偏移计算再转Pandas格式:

import pandas as pd
from datetime import datetime, timedelta

# 定义Windows纪元基准时间
win_epoch = datetime(1601, 1, 1)
# 假设待转换秒数存储在列win_seconds中
df["dt"] = pd.to_datetime(df["win_seconds"].apply(lambda s: win_epoch + timedelta(seconds=s)))

只要最终计算得到的时间落在Pandas Timestamp合法范围内,就不会触发超界报错。

方法2:使用Pandas Period类型转换(符合官方超界时间处理规范)

你提到的Period类型本身支持超出Timestamp范围的时间存储,可通过该类型完成偏移计算:

import pandas as pd

# 构造秒精度的Windows纪元Period对象
win_epoch_pd = pd.Period("1601-01-01", freq="S")
# 逐行偏移后转Timestamp
df["dt"] = df["win_seconds"].apply(lambda s: (win_epoch_pd + s).to_timestamp())

如果需要更高性能的批量处理,可使用PeriodIndex的向量化运算:

# 批量处理写法,避免逐行apply的性能损耗
df["dt"] = (pd.PeriodIndex([win_epoch_pd]*len(df), freq="S") + df["win_seconds"]).to_timestamp()

方法3:纪元偏移映射(性能最优)

Windows纪元(1601-01-01)与Pandas支持的Unix纪元(1970-01-01)的秒数差值为固定值11644473600,可直接基于该差值使用内置to_datetime转换,无需手动修改单条数据:

# 直接调用pandas内置向量化转换逻辑,性能最高
df["dt"] = pd.to_datetime(df["win_seconds"] - 11644473600, origin="unix")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 19:45:05