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

如何从ndarray中筛选出时间晚于5:00的时间戳?

解决numpy时间戳筛选问题

错误原因:datetime.utcfromtimestamp仅支持单个数值输入,无法直接处理numpy数组,直接传入数组会触发类型错误。

以下是两种不依赖pandas的正确实现方式:

方法一:向量化转换时间对象

通过np.vectorize包装时间转换函数,实现数组级别的时间戳转时间对象操作:

import numpy as np
from datetime import datetime

arr = np.array([1672713000, 1672716600, 1672720200, 1672723800, 1672727400, 1672731000])
threshold_time = datetime.strptime('5:00', '%H:%M').time()

# 向量化时间戳转UTC时间对象的函数
timestamp_to_time = np.vectorize(lambda ts: datetime.utcfromtimestamp(ts).time())
# 生成每个时间戳对应的时间数组
times = timestamp_to_time(arr)
# 筛选出5:00之后的时间戳
new_arr = arr[times > threshold_time]

方法二:纯数值计算(高效推荐)

直接计算时间戳对应的当天UTC秒数,避免创建datetime对象,性能更优:

import numpy as np

arr = np.array([1672713000, 1672716600, 1672720200, 1672723800, 1672727400, 1672731000])
# 5:00对应的当天UTC秒数(5*3600)
threshold_seconds = 18000
# 计算每个时间戳在当天的秒数(对一天总秒数86400取模)
day_seconds = arr % 86400
# 筛选符合条件的时间戳
new_arr = arr[day_seconds > threshold_seconds]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:03:21