Ros*_*yna 3 python time datetime pandas
我已经阅读了C.csv,该datetime列是一种object类型。
我想获取其中包含的每一行23:45:00,无论日期如何。我想datetime作为索引,我想将datetime索引转换为datetime64 [ns]。我相信pandas是为这种事情而设计的,但是我正在混合使用索引和数据类型。
import datetime as dt
import pandas as pd
df = pd.read_csv('C.csv', index_col = 'datetime', parse_dates=['datetime'])
Run Code Online (Sandbox Code Playgroud)
数据框:
C H L O OI V WAP
datetime
2017-04-22 09:23:00 39.48 39.48 39.48 39.48 0 0 39.48
2017-04-22 09:24:00 39.48 39.48 39.48 39.48 0 0 39.48
2017-04-22 09:25:00 39.48 39.48 39.48 39.48 0 0 39.48
2017-04-22 09:26:00 39.44 39.44 39.44 39.44 1 4 39.44
2017-04-22 09:27:00 39.48 39.48 39.48 39.48 3 2 39.48
Run Code Online (Sandbox Code Playgroud)
print(df)
datetime C H L O OI V WAP
0 2017-04-22 09:23:00 39.48 39.48 39.48 39.48 0 0 39.48
1 2017-04-22 09:24:00 39.48 39.48 39.48 39.48 0 0 39.48
2 2017-04-22 09:25:00 39.48 39.48 39.48 39.48 0 0 39.48
3 2017-04-22 09:26:00 39.44 39.44 39.44 39.44 1 4 39.44
4 2017-04-22 09:27:00 39.48 39.48 39.48 39.48 3 2 39.48
5 2017-04-23 09:25:00 39.48 39.48 39.48 39.48 3 2 39.48
Run Code Online (Sandbox Code Playgroud)
做datetime一个索引,并转换为日期时间dtype:
df.set_index('datetime', inplace=True)
df.index = pd.to_datetime(df.index)
print(df.index.dtype)
dtype('<M8[ns]')
Run Code Online (Sandbox Code Playgroud)
现在将匹配时间戳设置为所需时间,并按匹配条件进行过滤:
match_timestamp = "09:25:00"
df.loc[df.index.strftime("%H:%M:%S") == match_timestamp]
C H L O OI V WAP
datetime
2017-04-22 09:25:00 39.48 39.48 39.48 39.48 0 0 39.48
2017-04-23 09:25:00 39.48 39.48 39.48 39.48 3 2 39.48
Run Code Online (Sandbox Code Playgroud)
(时间戳23:45:00未包含在示例数据中,但要与此时间匹配,只需进行调整即可match_timestamp。)