Home > front end >  convert float to datetime when month is decimal place (YYYY.MM float)
convert float to datetime when month is decimal place (YYYY.MM float)

Time:02-11

This is my data:

d = pd.DataFrame({'date': [2021.01, 2021.02, 2021.03, 2021.04],
                   'value': [2, 3, 4, 1]})

d

enter image description here

I want to convert the date column to date. It is currently float with months in decimal place (YYYY.mm)

This does not work:

pd.to_datetime(d['date'], format='%Y.%m', errors='coerce').dt.to_period('m') 

CodePudding user response:

You can multiply by 100 and use an integer as input for to_datetime:

pd.to_datetime(d['date'].mul(100).astype(int), format='%Y%m').dt.to_period('m')

NB. it seems to work even without conversion to integer, but I would still do it, or use round to avoid floating point ambiguity (depending on the wanted output)

output:

0    2021-01
1    2021-02
2    2021-03
3    2021-04
Name: date, dtype: period[M]
  • Related