Pandas pd.to_datetime 只保留时间不日期

XY *_*XUE 4 python datetime pandas

我有一个数据框(Pandas),其中一列表示日期,格式如下:

import pandas as pd
import tushare as ts

data = ts.get_tick_data('600030',date='2019-06-28',src='tt') [['time','price','change','volume','amount']]
print(data.head())
Run Code Online (Sandbox Code Playgroud)

具体来说,我想使用 pd.to_datetime 将“时间”列转换为日期时间。

代码是:

  import pandas as pd
  import tushare as ts

  data = ts.get_tick_data('600030',date='2019-06-28',src='tt') [['time','price','change','volume','amount']]
  data.index=pd.to_datetime(data['time'])
  del data['time']
  print(data.head())
Run Code Online (Sandbox Code Playgroud)

结果如下:

                           price  change  volume    amount
   time                                                
   2019-06-29 09:25:04  23.85   -0.07    6825  16279485
   2019-06-29 09:30:02  23.85    0.00    2736   6529832
   2019-06-29 09:30:05  23.85    0.00    3964   9459955
   2019-06-29 09:30:08  23.85    0.00     665   1585346
   2019-06-29 09:30:11  23.87    0.02     348    830136
Run Code Online (Sandbox Code Playgroud)

我只想要日期时间样式的时间而不是日期。像这样:

          price  change  volume    amount
time                                     
09:25:04  23.85   -0.07    6825  16279485
09:30:02  23.85    0.00    2736   6529832
09:30:05  23.85    0.00    3964   9459955
09:30:08  23.85    0.00     665   1585346
09:30:11  23.87    0.02     348    830136
Run Code Online (Sandbox Code Playgroud)

所以我需要帮助。

taw*_*eel 7

尝试这个

df = pd.DataFrame(data={'date':['2019-06-29 09:25:04','2019-06-29 09:30:02'],
                       'col2':[2,3]})

df['time'] = pd.to_datetime(df['date']).dt.time
Run Code Online (Sandbox Code Playgroud)

如果你想把它作为索引,那么就这样做

df.set_index('time',inplace=True)
Run Code Online (Sandbox Code Playgroud)