Ank
Ank

Reputation: 1904

Pandas convert year column to date column

I have a pandas dataframe with a column containing years:

col1 col2 ... year ... coln
 -    -   ... 2020 ...  -
 -    -   ... 2021 ...  -
 -    -   ... 2022 ...  -

I want to convert this to date by mapping year to 1st date of that year, like:

col1 col2 ... year       ... coln
 -    -   ... 2020-01-01 ...  -
 -    -   ... 2021-01-01 ...  -
 -    -   ... 2022-01-01 ...  -

I tried this:

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

But it gives me this error:

ValueError: time data '2020' does not match format '%Y%m%d' (match)

How can I fix this?

Upvotes: 2

Views: 1698

Answers (2)

Soumendra Mishra
Soumendra Mishra

Reputation: 3653

You can try this:

df['year'] = df['year'].astype('str') + "-01-01"
print(df)

Upvotes: 1

jezrael
jezrael

Reputation: 862511

Use %Y for match year in format YYYY, but I think this parameter shoud be omitted:

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

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

Upvotes: 4

Related Questions