This error occurs when you try to call the string formatter function strftime() on a pandas Series. To fix the error use the Series dt accessor and only then call the strftime method. Here is an example:
your_df['your_column'].dt.strftime('%d/%m/%y')
Reproducing the Series has no strftime error
Let’s start by defining a very simple pandas DataFrame to show how to reproduce the attribute error exception:
import pandas as pd
stamps = pd.date_range(start='1/1/2023', periods = 4, freq = 'B' )
revenue = [10544, 19445, 12343, 13450]
sales = pd.DataFrame (dict (stamps = stamps, revenue = revenue))
sales .head()
Let’s look into our data set:
stamps | revenue | |
---|---|---|
0 | 2023-01-02 | 10544 |
1 | 2023-01-03 | 19445 |
2 | 2023-01-04 | 12343 |
3 | 2023-01-05 | 13450 |
Each column in the DataFrame is a pandas Series.
type(sales['stamps'])
This will return:
pandas.core.series.Series
Now, i would like to use the strftime() string formatter in order to change the datetime format of the values in my stamps column:
sales['stamps'].strftime('%d/%m/%y')
This returns an attribute error exception:
AttributeError: 'Series' object has no attribute 'strftime'
Here’s a screenshot from Jupyter Lab, you’ll get a similar error message in your Jupyter Notebook, PyCharm , VS COde, Spyder or other Python dev environments you might be using:
Solving the no attribute strftime exception
Before solving the issue, let’s understand the root cause for the exception. Strftime() role is to convert datetime objects to string objects. Therefore, when trying to invoke the function on a Series we get an attribute error. Luckily solving this error is very simple: pandas Series objects have a dt (datetime) accessor, that allows to invoke date related functions. They way you use the dt function is as following:
sales['stamps'].dt.strftime('%d/%m/%y')
This return the following Series of object – note the formatting of the dats as (dd/mm/yyyy):
0 02/01/23 1 03/01/23 2 04/01/23 3 05/01/23 Name: stamps, dtype: object
Frequently asked questions
Can i use the strftime function in case of missing dates in my Series?
Yes, we can write a lambda function to handle NAN values in our column:
sales['stamps'].apply(lambda s: s.strftime('%Y-%m-%d') if pd.notnull(s) else s)
What is the dt accessor in pandas?
We use the dt accessor to perform datatime related operations on a pandas Series. Couple of examples of using the dt accessor to extract date related information are: Series.dt.month and Series.dt.day.