How to Solve Python AttributeError: ‘Series’ object has no attribute ‘strftime’

by | Programming, Python, Tips

n Python, a Pandas Series is a one-dimensional labelled array capable of holding data of any type. Pandas Series is the same as a column in an Excel spreadsheet. If you have datetime objects in a Series that you want to convert to strings, you cannot use strftime() directly on the Series. If you try to call strftime() directly on a Series object, you will raise the AttributeError: ‘Series’ object has no attribute ‘strftime’.

You can format the datetime objects with the Pandas dt accessor. For example:

df['DateStr'] = df['DateObject'].dt.strftime['%d%m%Y')

You can also call the apply() method on the Series object with a lambda function, for example

df['DateStr'] = df['DateObject'].apply(lambda x: x.strtime('%d%m%Y')

This tutorial will go through the error in detail and how to solve it with code examples.


AttributeError: ‘Series’ object has no attribute ‘strftime’

AttributeError occurs in a Python program when we try to access an attribute (method or property) that does not exist for a particular object. The part “‘Series’ object has no attribute ‘strftime’” tells us that the Series object we are handling does not have the strftime attribute. The strftime() method belongs to the datetime module and returns a string representing a date and time. Pandas has an accessor object called dt which we can use to handle the datetime properties of Series values. The Pandas strftime() method is under dt.strftime(). The syntax for dt.strftime is as follows

Series.dt.strftime(date_format)

Parameters

  • date_format: Required. Date format string, e.g., '%d-%m-%d'

Returns

  • ndarray: a Numpy ndarray of formatted strings.

Example

Let’s look at an example where we try to convert a Series containing datetime objects to a specific format. First, we will create the Series:

import pandas as pd

# Create series

dates = pd.Series(['2021-05-30 08:45', '2020-3-23 12:30', '2022-02-24 10:30', '2008-3-17 09:25', '2010-12-17 00:00'])

# Create Index

idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']

# Set the Index

dates.index = idx

# Convert the data to datetime

dates = pd.to_datetime(dates)

# Print the series

print(dates)
Day 1   2021-05-30 08:45:00
Day 2   2020-03-23 12:30:00
Day 3   2022-02-24 10:30:00
Day 4   2008-03-17 09:25:00
Day 5   2010-12-17 00:00:00
dtype: datetime64[ns]

Then we will attempt to use strftime() to convert the dates in the series object to the specified format.

result = dates.strftime('%B %d, %Y, %r')
print(result)

Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-7-f471b596fb47> in <module>
----> 1 result = dates.strftime('%B %d, %Y, %r')
      2 print(result)

~/opt/anaconda3/lib/python3.8/site-packages/pandas/core/generic.py in __getattr__(self, name)
   5581         ):
   5582             return self[name]
-> 5583         return object.__getattribute__(self, name)
   5584 
   5585     def __setattr__(self, name: str, value) -> None:

AttributeError: 'Series' object has no attribute 'strftime'

The error occurs because we are trying to call the datetime strftime() method on a Series object. The Series equivalent for strftime() is under dt.strftime.

Solution #1: Use dt.strftime

To solve this error, we need to use dt.strftime instead of strftime to convert the datetime values to formatted strings. Let’s look at the revised code:

result = dates.dt.strftime('%B %d, %Y, %r')
print(result)

Let’s run the code to see the result:

Day 1         May 30, 2021, 08:45:00 AM
Day 2       March 23, 2020, 12:30:00 PM
Day 3    February 24, 2022, 10:30:00 AM
Day 4       March 17, 2008, 09:25:00 AM
Day 5    December 17, 2010, 12:00:00 AM
dtype: object

Solution #2: Use apply()

We can also use the Series method apply() to invoke the date strftime() function on each of the datetime values in the Series. We will define a lambda function to call the datetime strftime() method. Let’s look at the revised code:

result = dates.apply(lambda x: x.strftime('%B %d, %Y, %r')

print(result)

Let’s run the code to see the result:

Day 1         May 30, 2021, 08:45:00 AM
Day 2       March 23, 2020, 12:30:00 PM
Day 3    February 24, 2022, 10:30:00 AM
Day 4       March 17, 2008, 09:25:00 AM
Day 5    December 17, 2010, 12:00:00 AM
dtype: object

Summary

Congratulations on reading to the end of this tutorial! The AttributeError ‘Series’ object has no attribute ‘strftime’ occurs when you try to call the datetime strftime() method on a Series object.

To solve this error, you can use Pandas method pandas.Series.dt.strftime().

You can also use apply() to apply the datetime strftime method to each datetime object in the Series object, for example:

dates.apply(lambda x: x.strftime('%B %d, %Y, %r'))

For further reading on AttributeErrors involving the list object, go to the articles:

for further reading on pandas Series, go to the articles:

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee