Tom J Muthirenthi
Tom J Muthirenthi

Reputation: 3340

Pandas - Float to Date conversion YYYY-MM

I have a Column 'Date' which has values in the form YYYYMM, The Column date is of type float.

I wish to convert it in to date type as YYYY-MM.

When I try the below, it gives the error float is not sliceable.

df['Date'] = pd.to_datetime(df['Date'], format='%Y%m').dt.strftime('%Y%m')

Input Data

 Date(Float)
    201101.0
    201812.0

Output Required

Date(Date Type)
2011-01
2018-12

Upvotes: 1

Views: 2809

Answers (1)

Zero
Zero

Reputation: 76927

Use

In [26]: pd.to_datetime(df['Date'], format='%Y%m.0').dt.strftime('%Y-%m')
Out[26]:
0    2011-01
1    2018-12
Name: Date, dtype: object

Use pd.to_datetime(..., errors='coerce') to replace incomptabile values as NaT

Upvotes: 5

Related Questions