python-3.xpandasdatetime

How to extract data in a pandas dataframe with specific hour and minute?


The historical stock information of every minute in 2 years is read into a pandas dataframe with datetime as the index as shown below. I want to extract the rows with specific hour and minute, for instance, 09:30:00 every day. How to do it?

enter image description here

I don't care about the date. The only thing is to extract the data corresponding to 09:30:00 every day.

I want to know how to extract the data in a period as well. For instance, the data from 09:30:00 to 09:35:00.


Solution

  • Creating functions would solve your problem in following way:

    
    
    import pandas as pd
    from datetime import datetime, time
    
    def extract_by_time(df, time_str):
    
        df.index = pd.to_datetime(df.index)
        target_time = datetime.strptime(time_str, "%H:%M:%S").time()
        
        return df[df.index.time == target_time]
    
    def extract_time_range(df, start_time_str, end_time_str):
    
        df.index = pd.to_datetime(df.index)
    
        return df.between_time(start_time_str, end_time_str)
    
    

    Example DataFrame

    df = pd.read_csv("your_file.csv") 
    df['Date'] = pd.to_datetime(df['Date'])
    df.set_index('Date', inplace=True)
    
    df_930 = extract_by_time(df, "09:30:00")
    df_window = extract_time_range(df, "09:30:00", "09:35:00")