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

如何将Pandas DataFrame的datetime64[ns]列转换为datetime64[us]?

解决Pandas中datetime64[ns]转datetime64[us]类型不生效的问题

问题现象

尝试用astype转换DataFrame中datetime列的精度时,类型未发生变化:

>>> data[column].dtype.name
'datetime64[ns]'
>>> data[column] = data[column].astype('datetime64[us]')
>>> data[column].dtype.name
'datetime64[ns]'

原因

Pandas的astype方法处理datetime64类型时,会自动将列转换回默认的纳秒(ns)精度——因为Pandas的DatetimeArray底层默认以纳秒为单位存储,直接调用astype无法修改其底层存储精度。

可行解决方案

方案1:基于numpy数组转换后重构Series

先提取列的numpy数组转换精度,再重新构造Series并指定目标dtype:

data[column] = pd.Series(data[column].values.astype('datetime64[us]'), dtype='datetime64[us]')

方案2:通过整数转换重新生成datetime列

将ns精度的datetime转换为整数(纳秒数),除以1000得到微秒数,再用pd.to_datetime指定unit='us'生成us精度的列:

data[column] = pd.to_datetime(data[column].astype('int64') // 1000, unit='us')

验证转换结果

执行转换后,检查列类型:

>>> data[column].dtype.name
'datetime64[us]'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 19:02:05