Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python/Pandas: How do I convert from datetime64[ns] to datetime

I have a script that processes an Excel file. The department that sends it has a system that generated it, and my script stopped working.

I suddenly got the error Can only use .str accessor with string values, which use np.object_ dtype in pandas for the following line of code:

df['DATE'] = df['Date'].str.replace(r'[^a-zA-Z0-9\._/-]', '')

I checked the type of the date columns in the file from the old system (dtype: object) vs the file from the new system (dtype: datetime64[ns]).

How do I change the date format to something my script will understand?

I saw this answer but my knowledge about date formats isn't this granular.

like image 979
mattrweaver Avatar asked Aug 29 '16 13:08

mattrweaver


1 Answers

You can use apply function on the dataframe column to convert the necessary column to String. For example:

df['DATE'] = df['Date'].apply(lambda x: x.strftime('%Y-%m-%d'))

Make sure to import datetime module.

apply() will take each cell at a time for evaluation and apply the formatting as specified in the lambda function.

like image 91
Varun Pius Rodrigues Avatar answered Nov 15 '22 08:11

Varun Pius Rodrigues