dt.time.between在熊猫中返回一个空列

时间:2020-02-06 09:49:15

标签: python pandas datetime

slots = pd.DataFrame({'times': ['2020-02-01 18:40:00', '2020-02-01 08:40:00',
                                '2020-02-01 03:40:00', '2020-02-01 14:40:00',
                                '2010-05-05 22:00:00', '2018-03-08 23:00:00']})
print(slots)
slots['times'] = pd.to_datetime(slots.times)

from datetime import datetime
start = datetime.strptime('17:09:00', '%H:%M:%S').time()
print(start)
end = datetime.strptime('01:59:00', '%H:%M:%S').time()
print(end)


print(slots[slots['times'].dt.time.between(start, end)])


output: Empty DataFrame
Columns: [times]
Index: []

我正在获得空的数据框。有人可以指导还是有其他方法可以做到吗?

1 个答案:

答案 0 :(得分:1)

Pandas具有方法DataFrame.between_time,所以我建议使用它,并且还添加了DataFrame.set_indexDataFrame.reset_index,因为该方法可用于DatetimeIndex

df = (slots.set_index('times', drop=False)
           .between_time('17:09:00', '01:59:00')
           .reset_index(drop=True))
print (df)
                times
0 2020-02-01 18:40:00
1 2010-05-05 22:00:00
2 2018-03-08 23:00:00