How to filtering datetime column for hours interval (just hours) in pandas

Viewed 1144

I have a dataframe like the following:

datetimecolumn      valuecolumn
2017-01-03 01:00    17
2017-01-04 02:55    4
2017-01-04 05:55    4
2017-01-04 12:55    9
2017-01-04 16:55    88
2017-01-05 17:53    1
2017-01-06 10:22    74
2017-01-06 15:22    111

Now I need only the rows in which the hour is between 12:00 and 18:00. That would be:

datetimecolumn      valuecolumn
2017-01-04 12:55    9
2017-01-04 16:55    88
2017-01-05 17:53    1
2017-01-06 15:22    111

How can I apply that filter?

1 Answers

I assume you don't want to change column datetimecolumn format, so convert it to datetime and assign to s. Subtract s from its floor('D') to get only time portion and compare them with between to create a boolean mask m. Finally, slicing df using m

s = pd.to_datetime(df.datetimecolumn)
m = (s - s.dt.floor('D')).between(pd.Timedelta('12:00:00'), pd.Timedelta('18:00:00'))

df.loc[m]

Out[190]:
     datetimecolumn  valuecolumn
3  2017-01-04 12:55            9
4  2017-01-04 16:55           88
5  2017-01-05 17:53            1
7  2017-01-06 15:22          111
Related