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

numpy.array.tolist()转换datetime64返回int时间戳的解决方法

问题背景

dtype='datetime64[ns]'类型的numpy数组直接调用.tolist()返回整数时间戳的核心原因是:Python原生datetime对象最高仅支持微秒级时间精度,无法直接承载纳秒级的numpy datetime64值,因此numpy会降级返回纳秒级的Unix整数时间戳。
问题复现代码:

import numpy as np

my_array = np.array(['2017-06-28T22:47:51.213500000', '2017-06-28T22:48:37.570900000',
                     '2017-06-28T22:49:46.736800000', '2017-06-28T22:50:41.866800000',
                     '2017-06-28T22:51:17.024100000', '2017-06-28T22:51:24.038300000'], dtype='datetime64[ns]')

# 错误调用方式,返回整数时间戳
my_list = my_array.tolist()
# 输出: [1498690071213500000, 1498690117570900000, ...]
解决方案

方案1:直接从numpy数组转换(无额外依赖)

将数组先转为object类型,numpy会自动把datetime64值转换为Python原生datetime对象(纳秒部分自动截断到微秒精度,和Python datetime能力对齐),再转列表即可:

my_list = list(my_array.astype(object))

也可以先将datetime64的精度降到微秒级,再调用tolist(),效果完全一致:

my_list = my_array.astype('datetime64[us]').tolist()

转换后列表内元素均为标准datetime.datetime类型,可直接进行时间格式化、时间差计算等操作。

方案2:转换已得到的纳秒整数时间戳列表

如果已经拿到整数时间戳列表,可通过单位换算完成转换:列表内整数是从1970-01-01起算的纳秒级时间戳,除以1e9得到秒级时间戳后,用datetime.fromtimestamp转换即可:

from datetime import datetime

ts_list = [1498690071213500000,
           1498690117570900000,
           1498690186736800000,
           1498690241866800000,
           1498690277024100000,
           1498690284038300000]

dt_list = [datetime.fromtimestamp(ts / 1e9) for ts in ts_list]

方案3:pandas转换(适配复杂时间场景)

如果环境已安装pandas,可直接用pandas时间接口转换,支持完整纳秒精度处理,转Python原生datetime时会自动对齐到微秒精度:

import pandas as pd

dt_list = pd.to_datetime(my_array).to_pydatetime().tolist()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 07:37:29