Reputation: 769
I have a pandas dataframe which has datetime as its index (shown below)
['2018-02-13 11:55:00', '2018-02-13 12:00:00',
'2018-02-13 12:05:00', '2018-02-13 12:10:00',
'2018-02-13 12:15:00', '2018-02-13 12:20:00',
'2018-02-13 12:25:00', '2018-02-13 12:30:00',
'2018-02-13 12:35:00', '2018-02-13 12:40:00',
...
'2018-02-19 04:40:00', '2018-02-19 04:45:00',
'2018-02-19 04:50:00', '2018-02-19 05:05:00',
'2018-02-19 05:10:00', '2018-02-19 05:15:00',
'2018-02-19 05:20:00', '2018-02-19 05:25:00',
'2018-02-19 05:30:00', '2018-02-19 05:40:00'])
I would like to filter all the value which has time 12:00:00 for example, therefore I am looking for a return value of
['2018-02-13 12:00:00','2018-02-14 12:00:00','2018-02-15 12:00:00','2018-02-16 12:00:00','2018-02-17 12:00:00', '2018-02-18 12:00:00']
How can I perform such indexing please?
Upvotes: 1
Views: 1018
Reputation: 403040
Using the hour attribute is not enough if you want to find entries corresponding to noon at 12:00PM. Instead, compare your index/date-range with a datetime
object:
dt = pd.date_range('2018-02-13', '2018-02-19', freq='1h')
dt[dt.time == datetime.time(12)]
DatetimeIndex(['2018-02-13 12:00:00', '2018-02-14 12:00:00',
'2018-02-15 12:00:00', '2018-02-16 12:00:00',
'2018-02-17 12:00:00', '2018-02-18 12:00:00'],
dtype='datetime64[ns]', freq=None)
If you want to introduce a minutes or seconds component, simply change datetime.time(12)
to datetime.time(12, 5)
for 12:05:00PM, or datetime.time(12, 5, 30)
for 12:05:30PM, and so on.
Upvotes: 6
Reputation: 38415
You can filter using strftime
df[df.index.strftime('%H:%M:%S') == '12:00:00']
Upvotes: 2