rosefun
rosefun

Reputation: 1857

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

Upvotes: 3

Views: 3253

Answers (2)

jezrael
jezrael

Reputation: 862661

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

Upvotes: 4

Janko
Janko

Reputation: 147

df['time'].apply(lambda x: x.replace('-',''))

this should to the trick since your current values are just strings.

Upvotes: 1

Related Questions