15

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.

Community
  • 1
  • 1
mattrweaver
  • 729
  • 4
  • 14
  • 36

4 Answers4

9

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.

7

pd.to_datetime returns a Series of datetime64 dtype, as described here:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html

df['DATE'] = df['Date'].dt.date

or this:

df['Date'].map(datetime.datetime.date) 
theletz
  • 1,713
  • 2
  • 16
  • 22
Jose
  • 145
  • 1
  • 3
2

You can use pd.to_datetime

df['DATE'] = pd.to_datetime(df['DATE'])
Andrei Savin
  • 2,350
  • 4
  • 26
  • 40
Amandeep Singh
  • 503
  • 3
  • 5
2

Most of the answers here are outdated. I stumbled up on this issue and thought it is a bug in Pandas and raised an issue here.

https://github.com/pandas-dev/pandas/issues/52664

Turns out, datetime64 is not a valid dtype at all. So, we have to convert it to any of the valid dtypes below.

  • datetime64[s]
  • datetime64[ms]
  • datetime64[us]
  • datetime64[ns]

In pandas below version 2, s.astype('datetime64') doesn't throw any error, simply ignores it. Starting with pandas 2.0.0, it throws an error.

Cornelius Roemer
  • 3,772
  • 1
  • 24
  • 55
Chillar Anand
  • 27,936
  • 9
  • 119
  • 136