kdbqpython

kdb get last 1 hour records


i need to select and get rows which are related to previous 1 and 24 hours. to handle 24 hour i used this code. what about 1 hour how can i get that?

yesterday = datetime.now() - timedelta(1)
yesterday = datetime.strftime(yesterday, '%Y-%m-%d')

q.sendSync('{[x;z]select from trades where DateTime > x,symbol=z}', np.datetime64(yesterday,'D'),  np.string_('ETH-USDT'))

kdb saved dataframe

                     DateTime            symbol  
0     2022-04-13 12:59:00.171     b'ETH-USDT' 
1     2022-04-13 12:30:00.171     b'ETH-USDT'   
2     2022-04-13 10:55:00.171     b'ETH-USDT'       
3     2022-04-12 10:59:00.171     b'ETH-USDT'  
4     2022-04-10 10:53:00.185     b'ETH-USDT'  
5     2022-04-09 10:50:01.114     b'ETH-USDT'  

Solution

  • instead of yesterday you can use this as the time for the query - here we are just subtracting an hour from the current time and formatting it as a date and hour + minute rather than just a day

    hourago = datetime.strftime(datetime.now() - timedelta(hours = 1), '%Y-%m-%d %H:%M')
    
    q.sendSync('{[x;z]select from trades where DateTime > x,symbol=z}', np.datetime64(hourago,'ms'),  np.string_('ETH-USDT'))
    

    Its also worth noting you can do this purely in kdb without the need for the python date/time manipulation

    q.sendSync('{select from trades where DateTime > .z.p-0D01,symbol=x}', np.string_('ETH-USDT'))
    

    .z.p gives the current timestamp and -0D01 subtracts an hour from this time.