Select Page

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

by | Programming, Python, Tips

In Python, you can use the datetime library to work with dates and times. The datetime.strftime() method converts a datetime object containing a date and time to different string formats. You cannot call strftime() on a string object because strftime() is not a method of the String class. If you try to call strftime() on a string, you will raise the AttributeError: ‘str’ object has no attribute ‘strftime’.

To solve this error, you can create a datetime object by passing the string you want to format to the strptime() method then call the strftime() method on that object.

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


AttributeError: ‘str’ 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 “‘str’ object has no attribute ‘strftime’” tells us that the string object does not have the attribute strftime(). The strftime() method belongs to the DateTime class, and formats date objects into readable strings.

Python strftime() Syntax

The strftime() method converts datetime object to a formatted string. Let’s look at the syntax of the method

strftime(format)

Parameters

  • format: Required. The format codes to format the datetime object with.

Returns

  • Formatted string representation of the datetime object.

The format codes look like %Y, %m, %d, etc. To see the complete set of format codes supported on Python, you can read the Python standard library strftime documentation.

Python strptime() Syntax

The strptime() method creates a datetime object from the given string. You cannot create a datetime object from every string; the string must be in a specific format. Let’s look at the syntax for the strptime() method

strftime(string, format)

Parameters

  • string: Required. String to convert time object
  • format: Required. Format code to format the datetime object.

For further reading on using strptime(), go to the article: How to Solve Python ValueError: unconverted data remains.

Example

Let’s look at an example where we have a string representing a date. We want to format the string so that the date is in the order “Day/Month/Year“. We will try to call the strftime() method on the string to format it.

from datetime import datetime, date

a_date = '2022-01-17 13:56:22.000227'

format_date = a_date.strftime(a_date, "%d/%m/%Y")

Let’s run the code to see what happens:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-fc8b96063040> in <module>
      3 a_date = '2022-01-17 13:56:22.000227'
      4 
----> 5 format_date = a_date.strftime(a_date, "%d/%m/%Y")

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

The Python interpreter throws the AttributeError because we are trying to call a datetime method on a string.

Solution

To solve this error, we need to convert the string into a datetime object. We can use the strptime() method to get the datetime object in the same format as the string:

from datetime import datetime, date

a_date = '2022-01-17 13:56:22.000227'

date = datetime.strptime(a_date, '%Y-%m-%d %H:%M:%S.%f')

print(date)
print(type(date))

Let’s run the code to verify this step:

2022-01-17 13:56:22.000227
<class 'datetime.datetime'>

We can see that date is a datetime object. Then we will call the strftime() method on date.

formatted_date = date.strftime("%d/%m/%Y")

print(formatted_date)

Let’s run the code to see the result:

17/01/2022

We successfully formatted the datetime object to “Day/Month/Year“.

We can create an object of the datetime.datetime class and pass the date as integer arguments. The order of the arguments is year, month, day, hour, minute, second, microsecond. Year, month, and day are required arguments. Once we have the datetime object, we can call the strftime() method to format it. Let’s look at how we would do this for our date:

from datetime import datetime

date = datetime(2022, 1, 17, 13, 56, 22, 227)

formatted_date=date.strftime('%d/%m/%Y')

print(formatted_date)

Let’s run the code to get the result:

17/01/2022

We successfully formatted the datetime object to “Day/Month/Year“.

Summary

Congratulations on reading to the end of this tutorial! The error AttributeError: ‘str’ object has no attribute ‘strftime’ occurs when you try to call the strftime() method on a string as if it were a datetime object. To solve this error, convert the string containing the date to a datetime object using strptime() or create an object of the datetime class with the date as integer arguments.

For further reading on AttributeErrors, 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!

Research Scientist at Moogsoft | + posts

Suf is a research scientist at Moogsoft, specializing in Natural Language Processing and Complex Networks. Previously he was a Postdoctoral Research Fellow in Data Science working on adaptations of cutting-edge physics analysis techniques to data-intensive problems in industry. In another life, he was an experimental particle physicist working on the ATLAS Experiment of the Large Hadron Collider. His passion is to share his experience as an academic moving into industry while continuing to pursue research. Find out more about the creator of the Research Scientist Pod here and sign up to the mailing list here!