Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a float column to datetime with only year and month in Python?

I have a DATE column like this,

    DATE   CÓDIGO  ...          UNIDADE  VALOR
0  2009.06  10000.0  ...              NaN    NaN
1  2009.06  10100.0  ...    NÃO SE APLICA      .
2  2009.06  10101.0  ...               M2   0.46
3  2009.06  10102.0  ...               UN  15.15

I want to convert it to date format %Y%m.

Applying the code,

df['DATA'] = pd.to_datetime(df['DATA'], format='%Y.%m')

I get this,

0   1970-01-01 00:00:00.000002009
1   1970-01-01 00:00:00.000002009
2   1970-01-01 00:00:00.000002009
3   1970-01-01 00:00:00.000002009
4   1970-01-01 00:00:00.000002009
Name: DATA, dtype: datetime64[ns]

Thanks for the help!

like image 480
Marlon Henrique Teixeira Avatar asked Nov 30 '25 04:11

Marlon Henrique Teixeira


1 Answers

Convert to string first:

df['DATA'] = pd.to_datetime(df['DATA'].map('{:.2f}'.format), format='%Y.%m')

As it is, pd.to_datetime considers the float value is milliseconds since 1970.

like image 117
IanS Avatar answered Dec 02 '25 18:12

IanS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!