如果给定一个np.datetime64
类型的数据,如何获取时间前后的一段时间?
例如,如果将 np.datetime64('2020-04-01T21:32')
赋给函数,我希望函数返回 np.datetime64('2020- 04-01T21:30')
和 np.datetime64('2020-04-01T21:39')
- 给定时间前后 10 分钟。
有什么办法可以用 numpy 做到这一点吗?
最佳答案
Numpy 没有像 Pandas 那样的内置时间段。
如果您只需要两个时间戳,则以下函数应该可以工作。
def ten_minutes_around(t):
t = ((t.astype('<M8[m]') # Truncate time to integer minute representation
.astype('int') # Convert to integer representation
// 10) * 10 # Remove any sub 10 minute minutes
).astype('<M8[m]') # convert back to minute timestamp
return np.array([t, t + np.timedelta64(10, 'm')]).T
例如:
for t in [np.datetime64('2020-04-01T21:32'), np.datetime64('2052-02-03T13:56:03.172')]:
s, e = ten_minutes_around(t)
print(s, t, e)
给出:
2020-04-01T21:30 2020-04-01T21:32 2020-04-01T21:40
2652-02-03T13:50 2652-02-03T13:56:03.172 2652-02-03T14:00
和
ten_minutes_around(np.array([
np.datetime64('2020-04-01T21:32'),
np.datetime64('2652-02-03T13:56:03.172'),
np.datetime64('1970-04-01'),
]))
给予
array([['2020-04-01T21:30', '2020-04-01T21:40'],
['2652-02-03T13:50', '2652-02-03T14:00'],
['1970-04-01T00:00', '1970-04-01T00:10']], dtype='datetime64[m]')
关于python - 如何获得使用 Numpy 的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60985170/