python-2.7datetimepandasdatetime64

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.


Solution

  • You can use pd.to_datetime

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