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?
Use DataFrame. astype() Method to Convert Integer to Datetime Format. DataFrame. astype() method is also used to convert integer to datetime formate.
Use pandas.to_datetime() method is used to change String/Object time to date type (datetime64[ns]). This method is smart enough to change different formats of the String date column to date.
Pandas DataFrame astype() Method The astype() method returns a new DataFrame where the data types has been changed to the specified type.
strftime(*args, **kwargs)[source] Convert to Index using specified date_format. Return an Index of formatted strings specified by date_format, which supports the same string format as the python standard library. Details of the string format can be found in python string format doc.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With