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

Pandas Timestamp异常省略毫秒、微秒和纳秒问题求助

Pandas带时区Timestamp转Epoch纳秒数异常问题

问题描述

更新Anaconda环境后,使用Pandas将带时区的可读日期时间转换为Epoch纳秒级时间戳时出现异常:

更新前执行以下代码可得到纳秒级整数:

ts = pd.Timestamp('2021-04-25 12:13:30', tz='Europe/Berlin')
ts_new = np.int64(ts.asm8)

结果:1619345610000000000

但更新后(当前版本:pandas 2.0.3,numpy 1.24.3)结果变为:

结果:1619345610

而无时区的转换仍正常:

ts = pd.to_datetime('2021-04-25 12:13:30')
ts_new = np.int64(ts.asm8)

结果:1619352810000000000

根据Pandas文档,asm8应返回纳秒级numpy datetime64格式,但当前带时区的场景下精度降为秒级,不符合预期。

原因分析

这是Pandas 2.0+版本的行为变化,而非操作错误或bug:

  • 对于带时区的Timestamp,当时间戳无毫秒/微秒/纳秒部分时,asm8会自动采用更紧凑的精度(秒级datetime64[s])存储,而非强制纳秒级。
  • 无时区的Timestamp仍默认使用纳秒级精度,因此转换结果正常。

解决方案

有两种可靠方法获取纳秒级Epoch时间戳:

方法1:使用Timestamp.value属性

value属性直接返回纳秒级整数,不受精度优化影响:

ts = pd.Timestamp('2021-04-25 12:13:30', tz='Europe/Berlin')
ts_new = ts.value
print(ts_new)  # 输出:1619345610000000000

方法2:强制转换asm8到纳秒精度

将asm8显式转换为纳秒级datetime64类型后再转整数:

ts = pd.Timestamp('2021-04-25 12:13:30', tz='Europe/Berlin')
ts_new = np.int64(ts.asm8.astype('datetime64[ns]'))
print(ts_new)  # 输出:1619345610000000000

版本信息

INSTALLED VERSIONS
------------------
commit           : 0f437949513225922d851e9581723d82120684a6
python           : 3.11.3.final.0
python-bits      : 64
OS               : Windows
OS-release       : 10
Version          : 10.0.19045
machine          : AMD64
processor        : Intel64 Family 6 Model 158 Stepping 9, GenuineIntel
byteorder        : little
LC_ALL           : None
LANG             : en
LOCALE           : de_DE.cp1252

pandas           : 2.0.3
numpy            : 1.24.3
pytz             : 2022.7
dateutil         : 2.8.2
setuptools       : 67.8.0
pip              : 23.1.2
Cython           : None
pytest           : 7.4.0
hypothesis       : None
sphinx           : 5.0.2
blosc            : None
feather          : None
xlsxwriter       : None
lxml.etree       : 4.9.2
html5lib         : None
pymysql          : None
psycopg2         : None
jinja2           : 3.1.2
IPython          : 8.15.0
pandas_datareader: None
bs4              : 4.12.2
bottleneck       : 1.3.5
brotli           : 
fastparquet      : None
fsspec           : 2023.4.0
gcsfs            : None
matplotlib       : 3.7.2
numba            : 0.57.1
numexpr          : 2.8.4
odfpy            : None
openpyxl         : 3.0.10
pandas_gbq       : None
pyarrow          : None
pyreadstat       : None
pyxlsb           : None
s3fs             : 2023.4.0
scipy            : 1.11.1
snappy           : 
sqlalchemy       : 1.4.39
tables           : 3.8.0
tabulate         : 0.8.10
xarray           : 2023.6.0
xlrd             : None
zstandard        : 0.19.0
tzdata           : 2023.3
qtpy             : 2.2.0
pyqt5            : None

内容的提问来源于stack exchange,提问作者Günter Weber

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 20:13:22