Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas pd.to_datetime only keep time do not date

I have a dataframe(Pandas), with a column representing dates, in the following format:

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())

Specifically, I would like to use pd.to_datetime convert the 'time' column to datetime.

The code are:

  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())

The results are as follow:

                           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

I only want the time with the datetime style but do not the date. Like this:

          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

So I need the the help.

like image 992
XY XUE Avatar asked Jun 29 '19 10:06

XY XUE


Video Answer


1 Answers

try this

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

if you want to make this as index then just do

df.set_index('time',inplace=True)
like image 153
tawab_shakeel Avatar answered Oct 01 '22 08:10

tawab_shakeel