Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert int64 to datetime in pandas

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?

like image 206
HHH Avatar asked Jul 26 '18 17:07

HHH


People also ask

How do you convert int to datetime in Python?

Use DataFrame. astype() Method to Convert Integer to Datetime Format. DataFrame. astype() method is also used to convert integer to datetime formate.

How do I convert a string to a date in pandas?

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.

What does Astype do in pandas?

Pandas DataFrame astype() Method The astype() method returns a new DataFrame where the data types has been changed to the specified type.

What is Strftime in pandas?

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.


1 Answers

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
like image 185
jpp Avatar answered Oct 31 '22 01:10

jpp