How to change the datetime format in pandas

前端 未结 8 1895
萌比男神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:51

    Compared to the first answer, I will recommend to use dt.strftime() first, then pd.to_datetime(). In this way, it will still result in the datetime data type.

    For example,

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

提交回复
热议问题