Aaron E Larson
Aaron E Larson

Reputation: 41

Wrong year format for pd.to_datetime format in pandas

Using pandas, I have a dataframe with column 'REPAIR_YEAR' values listed such as:

2018
2018
2019
2020
2021

I want to set this to a year value, so I run

df['REPAIR_YEAR'] = pd.to_datetime(df['REPAIR_YEAR'])

Instead of 2018, 2019, 2020, o2 2021, the result is:

1970-01-01 00:00:00.000002018
1970-01-01 00:00:00.000002018
1970-01-01 00:00:00.000002019
1970-01-01 00:00:00.000002020
1970-01-01 00:00:00.000002021

How can I make the results show the correct year and not 1970?

Upvotes: 1

Views: 52

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195543

Use format="%Y":

df["REPAIR_YEAR"] = pd.to_datetime(df["REPAIR_YEAR"], format="%Y")
print(df)

Prints:

  REPAIR_YEAR
0  2018-01-01
1  2018-01-01
2  2019-01-01
3  2020-01-01
4  2021-01-01

Upvotes: 1

Related Questions