首页 > 解决方案 > dt.time.between 在 pandas 中返回一个空列

问题描述

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: []

我得到空的数据框。有人可以指导还是有其他方法可以做到这一点。

标签: pythonpandasdatetime

解决方案


Pandas 有方法DataFrame.between_time,所以我建议使用它,也添加了它,DataFrame.set_index因为DataFrame.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

推荐阅读