Python:按时间过滤python数据帧

时间:2021-01-03 11:03:08

标签: python

我有以下数据框,其中有一列 not index 称为时间戳。

0         2019-09-02 09:14:00.125
1         2019-09-02 09:14:00.125
2         2019-09-02 09:14:00.125
3         2019-09-02 09:14:00.125
4         2019-09-02 09:14:00.125
         
1096674   2019-09-20 16:32:00.157
1096675   2019-09-20 16:34:06.988
1096676   2019-09-20 16:34:15.352
1096677   2019-09-20 16:34:15.352
1096678   2019-09-20 16:34:15.551
Name: Timestamp, Length: 1096679, dtype: datetime64[ns]

我想提取数据框中所有日期的 09:13:00.17011:45:00.234 之间的所有行。

我尝试了以下

df.loc[(df['Timestamp'] >='09:13:00.170') & (df['Timestamp'] <='11:45:00.234'),:]

但它收到一个空数据帧作为回报,但前几行 09:14:00.xxx 大于 09:13:00.170,因此应该包括它们。然而他们不是。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

我相信您是在与字符串进行比较。您可以使用 strptime() 将字符串格式化为日期时间。

import datetime

start = datetime.datetime.strptime('2019-09-02 09:13:00.170', '%Y-%m-%d %H:%M:%S.%f')
end = datetime.datetime.strptime('2019-09-02 11:45:00.234', '%Y-%m-%d %H:%M:%S.%f')

df[(df['Timestamp'] >=start) & (df['Timestamp'] <= end)]