How to change the datetime format in pandas

前端 未结 8 1894
萌比男神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)
    
    0 讨论(0)
  • 2020-11-21 23:53

    You can try this it'll convert the date format to DD-MM-YYYY:

    df['DOB'] = pd.to_datetime(df['DOB'], dayfirst = True)
    
    0 讨论(0)
提交回复
热议问题