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

后端 未结 4 1581
有刺的猬
有刺的猬 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 00:53

    If your series is s, then this will create such a DataFrame:

    pd.DataFrame({
        'date': pd.to_datetime(s).dt.date,
        'time': pd.to_datetime(s).dt.time})
    

    as once you convert the series using pd.to_datetime, then the dt member can be used to extract the parts.


    Example

    import pandas as pd
    
    s = pd.Series(['2015-05-13 23:53:00', '2015-05-13 23:53:00'])
    >>> pd.DataFrame({
        'date': pd.to_datetime(s).dt.date,
        'time': pd.to_datetime(s).dt.time})
        date    time
    0   2015-05-13  23:53:00
    1   2015-05-13  23:53:00
    

提交回复
热议问题