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!

Upvotes: 3

Views: 7110

Answers (2)

IanS
IanS

Reputation: 16251

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.

Upvotes: 7

BENY
BENY

Reputation: 323306

Adding astype(str)

pd.to_datetime(df['DATE'].astype(str), format='%Y.%m')
Out[710]: 
0   2009-06-01
1   2009-06-01
2   2009-06-01
3   2009-06-01
Name: DATE, dtype: datetime64[ns]

Upvotes: 3

Related Questions