pythonpandasdatetimedataframeformat-conversion

Pandas:How to convert date format %Y-%M-%D into %Y%M%D?


I have a dataframe, which can be shown as follows:

Input

import pandas as pd 
df=pd.DataFrame({'time':['2018-07-04','2018-04-03',]})
print('df\n',df)

Output

         time
0  2018-07-04
1  2018-04-03

Expected

     time
0  20180704
1  20180403

Solution

  • Use to_datetime with strftime:

    df['time'] = pd.to_datetime(df['time']).dt.strftime('%Y%m%d')
    print (df)
           time
    0  20180704
    1  20180403
    

    Solution with replace:

    df['time'] = df['time'].str.replace('-','')
    print (df)
           time
    0  20180704
    1  20180403