Search code examples
pythonpandastimedeltastrptimestrftime

Compare time (hours and minutes) when looping in dataframe


I have the following sample data:

custom_date_parser = lambda x:datetime.strptime(x, "%m/%d/%Y %H:%M") 
df = pd.read_csv('sample.csv', index_col = 0, parse_dates = ['date'], date_parser = custom_date_parser)

|         date          | value   |
| -------------------   | --------|
| 2021-12-06 08:30:00   | 100     |
| 2021-12-06 08:35:00   | 150     |
| 2021-12-06 08:40:00   | 120     |
| 2021-12-06 08:45:00   | 90      |
| 2021-12-06 08:50:00   | 80      |
...................................
| 2021-12-09 08:30:00   | 220     |
| 2021-12-09 08:35:00   | 250     |
| 2021-12-09 08:40:00   | 260     |
| 2021-12-09 08:45:00   | 290     |
| 2021-12-09 08:50:00   | 300     |

I want to loop through the dataframe and print the number in 'value' column if the hours and minutes '08:40:00' are in the index column. I've tried funny stuff like:

for i in df.index:
    if '08:40:00' in [i]:
        print(df.value[i])

Solution

  • Since you've parsed it into a datetime object, you can check the hour and the minute, filter the dataframe to those rows that match and print the corresponding values.

    for x in df.loc[(df['date'].dt.hour.eq(8)) & (df['date'].dt.minute.eq(40))]['value']:
        print(x)