pythonnumpynumpy-ndarray

How to pick timestamps from ndarray if time() is bigger than 5:00


I have an ndarray of timestamps. I need to pick timestamps if they represent a time after 5:00.

The sample code is:

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)

However, when I try the following code, I get the this error:

TypeError: only integer scalar arrays can be converted to a scalar index

How to query ndarray correctly in this case? I can't use pandas to solve this issue.


Solution

  • Such solution worked for me:

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

    The output is:

    [1672723800 1672727400 1672731000]