How to solve the AttributeError: ‘Series’ object has no attribute ‘strftime’ error?

This error occurs when you call the string formatter function strftime() on a pandas Series.

Reproducing the error

Let’s start by defining a very simple pandas DataFrame 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 Dataset:

stampsrevenue
02023-01-0210544
12023-01-0319445
22023-01-0412343
32023-01-0513450

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

Follow up learning

How to cast float objects to strings in Python and pandas?