Reputation: 6485
I have a pandas dataframe that has a column of type int64 but this columns represets date, e.g. 20180501. I'd like to convert this column to datetime and I'm having the following code but it returns an error message
df['new_date'] = pd.to_datetime(df['old_date'].astype('str'), format = '%y%m%d')
I'm getting the following error message
ValueError: unconverted data remains: 0501
How can I fix my code?
Upvotes: 7
Views: 28316
Reputation: 1
It could be that the problem arises due to a format error at some places in the dataframe.
You could try setting the parameter errors="coerce" to avoid converting those entries and setting them to NaT.
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html
Upvotes: 0
Reputation: 164813
You need a capital Y
. See Python's strftime directives for a complete reference.
df = pd.DataFrame({'old_date': [20180501, 20181230, 20181001]})
df['new_date'] = pd.to_datetime(df['old_date'].astype(str), format='%Y%m%d')
print(df)
old_date new_date
0 20180501 2018-05-01
1 20181230 2018-12-30
2 20181001 2018-10-01
Upvotes: 10