What Does AttributeError: Module ‘datetime’ Has No Attribute ‘strptime’ Mean?

What does AttributeError: module 'datetime' has no attribute 'strptime' mean and how can you easily fix it?

When parsing a string and transforming that to a date you can make use of the function strptime in the datetime module.

To use this function simply import datetime as you normally would with any module, and use the function as follows:

>>> import datetime
>>> datetime.datetime.strptime("16/06/22", "%d/%m/%y")
datetime.datetime(2022, 6, 16, 0, 0)

Notice in the above code that the function strptime is found within the module datetime and class datetime , therefore, if your code just has import datetime at the top you will need to enter the module and class followed by the function.

A workaround is to import the module and class in your import declaration, like so:

>>> from datetime import datetime
>>> datetime.strptime("17/08/22", "%d/%m/%y")
datetime.datetime(2022, 8, 17, 0, 0)

Notice in this code that the strptime only has the direct class datetime to reference as the import declaration on pulled that class from the module.

Another popular mistake with this approach is thinking you can import strptime from the import declaration, like so:

>>> from datetime import strptime
ImportError: cannot import name 'strptime' from 'datetime' 

As you can see from this error you cannot strptime as it’s a function in the datetime class found in the datetime module.

Summary

If you’re experiencing issues with the strptime method check your import declaration for datetime . Have you imported the module and class or just the module? If you’ve imported the module and class using from datetime import datetime then your function call will be datetime.strptime() , otherwise if you’ve used import datetime you would need to reference the module and class along with the function, like so: datetime.datetime.strptime() .

Photo of author
Ryan Sheehy
Ryan has been dabbling in code since the late '90s when he cut his teeth exploring VBA in Excel. Having his eyes opened with the potential of automating repetitive tasks, he expanded to Python and then moved over to scripting languages such as HTML, CSS, Javascript and PHP.