How to get a period of time with Numpy?

Viewed 678

If a np.datetime64 type data is given, how to get a period of time around the time?

For example, if np.datetime64('2020-04-01T21:32') is given to a function, I want the function to return np.datetime64('2020-04-01T21:30') and np.datetime64('2020-04-01T21:39') - 10 minutes around the given time.

Is there any way to do this with numpy?

2 Answers

To do so we can get the minute from the given time and subtract it from the given time to get the starting of the period and add 9 minutes to get the ending time of the period.

import numpy as np
time = '2020-04-01T21:32'
dt = np.datetime64(time) 
base = (dt.tolist().time().minute) % 10 // base would be 3 in this case

start = dt - np.timedelta64(base,'m')
end = start + np.timedelta64(9,'m')
print(start,end,sep='\n')

I hope this helps.

Numpy does not have a built in time period like Pandas does.

If all you want are two time stamps the following function should work.

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 example:

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)

gives:

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

and

ten_minutes_around(np.array([
    np.datetime64('2020-04-01T21:32'),
    np.datetime64('2652-02-03T13:56:03.172'),
    np.datetime64('1970-04-01'),
]))

gives

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]')
Related