Getting error AttributeError: 'str' object has no attribute 'strftime'

Viewed 1468

I'm getting an error

'str' object has no attribute 'strftime'

from this code of mine:

from datetime import datetime, date
analysis_dataframe.loc[:,'order_period'] = analysis_dataframe.date.apply(lambda x: x.strftime('%Y-%m'))
analysis_dataframe.head(10)

and I have a column "date" with dates in format like that:

column date

How can I fix this error?

Thank you

2 Answers

strftime is a member function of datetime class. You called the function on x: x.strftime('%Y-%m'). The error message suggests that x is an object of type str, i.e. it is a string.

It looks like your analysis_dataframe.date is an array / series of formatted datetime strings instead of the actual datetime. Therefore, in order to use the strftime function, you need to parse the date string into a datetime object first, then call the strftime function:

... = analysis_dataframe.date.apply(lambda x: datetime.fromisoformat(x).strftime('%Y-%m'))

First of all, since strftime method expects pandas datatime object first convert it:

analysis_dataframe.date  = pd.to_datetime(analysis_dataframe.date)

Now you command should work

analysis_dataframe.order_period = analysis_dataframe.date.apply(lambda x: x.strftime('%Y-%m'))
Related