我有一个时间戳数组。如果时间戳代表 5:00 之后的时间,我需要选择时间戳。
示例代码为:
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()
new_arr = np.where(datetime.utcfromtimestamp(arr).time() > threshold_time)
但是,当我尝试以下代码时,我收到此错误:
TypeError: only integer scalar arrays can be converted to a scalar index
这种情况下如何正确查询ndarray?我无法使用 pandas 来解决这个问题。
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()
func = np.vectorize(datetime.utcfromtimestamp)
# Create a boolean mask for accurate filtering
mask = (func(arr) > datetime.combine(datetime.today(), threshold_time)).astype(bool)
# Use the boolean mask to filter the array
new_arr = arr[mask]
print(new_arr) # This will output the filtered timestamps
这样的解决方案对我有用:
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()
pick_time = np.vectorize(lambda x: datetime.utcfromtimestamp(x).time())
new_arr = np.where(pick_time(arr) > threshold_time)
print(arr[new_arr])
输出为:
[1672723800 1672727400 1672731000]