How do I extract the date/year/month from pandas dataframe?

后端 未结 1 1537
我在风中等你
我在风中等你 2021-01-12 19:25

I\'m trying to extract year/date/month info from the \'date\' column in pandas dataframe. Here is my sample code:

from datetime import datetime
def date_spli         


        
1条回答
  •  再見小時候
    2021-01-12 20:03

    It seems you need to_datetime:

    print (df['date'].dtype)
    object
    
    df['date'] = pd.to_datetime(df['date'])
    
    print (df['date'].dtype)
    datetime64[ns]
    

    If need extract year, month and day to new columns:

    df['year'] = df['date'].dt.year
    df['month'] = df['date'].dt.month
    df['day'] = df['date'].dt.day
    

    If need list of dates:

    listdate = df['date'].dt.date.tolist()
    print (listdate)
    
    [datetime.date(2017, 9, 5), 
     datetime.date(2017, 9, 4),
     datetime.date(2017, 9, 3), 
     datetime.date(2017, 9, 2),
     datetime.date(2017, 9, 1)]
    

    0 讨论(0)
提交回复
热议问题