Python/Pandas convert string to time only

后端 未结 4 484
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 20:38

I have the following Pandas dataframe in Python 2.7.

import pandas as pd
trial_num = [1,2,3,4,5]
sail_rem_time = [\'11:33:11\',\'16:29:05\',\'09:37:56\',\'21         


        
相关标签:
4条回答
  • 2020-12-02 21:13

    This seems to work:

    dfc['Time_of_Sail'] = pd.to_datetime(dfc['Time_of_Sail'], format='%H:%M:%S' ).apply(pd.Timestamp)

    0 讨论(0)
  • 2020-12-02 21:14

    These two lines:

    dfc['Time_of_Sail'] = pd.to_datetime(dfc['Time_of_Sail'])
    dfc['Time_of_Sail'] = [time.time() for time in dfc['Time_of_Sail']]
    

    Can be written as:

    dfc['Time_of_Sail'] = pd.to_datetime(dfc['Time_of_Sail'],format= '%H:%M:%S' ).dt.time
    
    0 讨论(0)
  • 2020-12-02 21:18

    If you just want a simple conversion you can do the below:

    import datetime as dt
    
    dfc.Time_of_Sail = dfc.Time_of_Sail.astype(dt.datetime)
    

    or you could add a holder string to your time column as below, and then convert afterwards using an apply function:

    dfc.Time_of_Sail = dfc.Time_of_Sail.apply(lambda x: '2016-01-01 ' + str(x))
    dfc.Time_of_Sail = pd.to_datetime(dfc.Time_of_Sail).apply(lambda x: dt.datetime.time(x))
    
    0 讨论(0)
  • 2020-12-02 21:20

    Using to_timedelta,we can convert string to time format(timedelta64[ns]) by specifying units as second,min etc.,

    dfc['Time_of_Sail'] = pd.to_timedelta(dfc['Time_of_Sail'], unit='s')
    
    0 讨论(0)
提交回复
热议问题