Attributeerror: module datetime has no attribute strptime error occurs because strptime is not directly available in datetime package. Actually, datetime has a class by the name of datetime inside the same. If we make an improper invoking statement, we get the same error. In this article, we will understand this error with a practical examples. We will also see the easiest way to fix this issue. So let’s begin.
attributeerror: module datetime has no attribute strptime ( Root Cause ) –
In order to understand this error, we will firstly see a code sample and run the same. Then on the basis of that, we will understand the root cause.
import datetime date_var = '2022-06-19' datetime.strptime(date_var, "%Y-%m-%d")
when we run the code we get the above error.
Solution for module datetime has no attribute strptime –
Trick 1 :
As I already explained to you that this error is just because of the wrong caller statement. Firstly let’s quickly see the solution.
import datetime date_var = '2022-06-19' datetime.datetime.strptime(date_var, "%Y-%m-%d")
Here we made a small change in the code. We first use datetime module and datetime class then strptime attribute. That fixed our error. Earlier if we look closely, you will find that we directly used datetime.strptime which is ultimately calling attribute from the module. This is technically wrong. That’s why we were getting this error.
Trick 2 –
We can fix this issue by changing the import statement. Actually, we will import the class directly then the same syntax will work. Let’s see practically.
Now the question gets up why this common mistake developer does a large scale. The reason is very simple is name confusion. Typically module and the class name are usually different always. This is a bit different but technically correct too. I hope now we are clear on how to fix this python exception.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.