Reputation: 187
I have a pandas DataFrame with a 'date' column, which uses this format:
2015-01-01 04:00:00
2015-01-01 05:00:00
2015-01-01 06:00:00
2015-01-01 07:00:00
...
2015-01-02 04:00:00
2015-01-02 05:00:00
2015-01-02 06:00:00
2015-01-02 07:00:00
I want to filter the DataFrame so I only keep the rows with a stated time, e.g. 06:00:00
2015-01-01 06:00:00
2015-01-02 06:00:00
I tried things like
df['date'] = pd.to_datetime(df['date'])
df = df[df['date'].time() == datetime.time(6)]
But they don't work.
How can I achieve that?
Upvotes: 2
Views: 2422
Reputation: 393903
You can use the datetime
attribute accessor to access the hour
attribute to filter the df once the dtype is a datetime:
In [141]:
t="""2015-01-01 04:00:00
2015-01-01 05:00:00
2015-01-01 06:00:00
2015-01-01 07:00:00
2015-01-02 04:00:00
2015-01-02 05:00:00
2015-01-02 06:00:00
2015-01-02 07:00:00"""
s = pd.read_csv(io.StringIO(t), parse_dates=[0], header=None, names=['date'])
s[s['date'].dt.hour == 6]
Out[141]:
date
2 2015-01-01 06:00:00
6 2015-01-02 06:00:00
Upvotes: 1