How to change the datetime format in pandas

前端 未结 8 1885
萌比男神i
萌比男神i 2020-11-21 23:26

My dataframe has a DOB column (example format 1/1/2016) which by default gets converted to pandas dtype \'object\': DOB object

8条回答
  •  抹茶落季
    2020-11-21 23:36

    You can use dt.strftime if you need to convert datetime to other formats (but note that then dtype of column will be object (string)):

    import pandas as pd
    
    df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
    print (df)
             DOB
    0  26/1/2016 
    1  26/1/2016
    
    df['DOB'] = pd.to_datetime(df.DOB)
    print (df)
             DOB
    0 2016-01-26
    1 2016-01-26
    
    df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
    print (df)
             DOB        DOB1
    0 2016-01-26  01/26/2016
    1 2016-01-26  01/26/2016
    

提交回复
热议问题