1

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
IanS
  • 15,771
  • 9
  • 60
  • 84
Tom J Muthirenthi
  • 3,028
  • 7
  • 40
  • 60

1 Answers1

5

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

Zero
  • 74,117
  • 18
  • 147
  • 154