0

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
  • 14,753
  • 9
  • 56
  • 81
Tom J Muthirenthi
  • 2,613
  • 5
  • 34
  • 52

1 Answers1

4

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
  • 66,763
  • 15
  • 141
  • 151