How can I split a DataFrame column with datetimes into two columns: one with dates and one with times of the day?

后端 未结 4 1582
有刺的猬
有刺的猬 2021-01-19 00:26

I have a data frame called data, which has a column Dates like this,

                 Dates
0  2015-05-13 23:53:00
1  2015-05-13 23         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-19 01:05

    If type of column Dates is string, convert it by to_datetime. Then you can use dt.date, dt.time and last drop original column Dates:

    print df['Dates'].dtypes
    object
    print type(df.at[0, 'Dates'])
    
    
    df['Dates'] = pd.to_datetime(df['Dates'])
    
    print df['Dates'].dtypes
    datetime64[ns]
    
    print df
                    Dates
    0 2015-05-13 23:53:00
    1 2015-05-13 23:53:00
    2 2015-05-13 23:33:00
    3 2015-05-13 23:30:00
    4 2015-05-13 23:30:00
    
    df['Date'] = df['Dates'].dt.date
    df['Time'] = df['Dates'].dt.time
    
    df = df.drop('Dates', axis=1)
    print df
             Date      Time
    0  2015-05-13  23:53:00
    1  2015-05-13  23:53:00
    2  2015-05-13  23:33:00
    3  2015-05-13  23:30:00
    4  2015-05-13  23:30:00
    

提交回复
热议问题