python – AttributeError: datetime module has no attribute strptime

python – AttributeError: datetime module has no attribute strptime

If I had to guess, you did this:

import datetime

at the top of your code. This means that you have to do this:

datetime.datetime.strptime(date, %Y-%m-%d)

to access the strptime method. Or, you could change the import statement to this:

from datetime import datetime

and access it as you are.

The people who made the datetime module also named their class datetime:

#module  class    method
datetime.datetime.strptime(date, %Y-%m-%d)

Use the correct call: strptime is a classmethod of the datetime.datetime class, its not a function in the datetime module.

self.date = datetime.datetime.strptime(self.d, %Y-%m-%d)

As mentioned by Jon Clements in the comments, some people do from datetime import datetime, which would bind the datetime name to the datetime class, and make your initial code work.

To identify which case youre facing (in the future), look at your import statements

  • import datetime: thats the module (thats what you have right now).
  • from datetime import datetime: thats the class.

python – AttributeError: datetime module has no attribute strptime

I got the same problem and it is not the solution that you told. So I changed the from datetime import datetime to import datetime. After that with
the help of datetime.datetime I can get the whole modules correctly. I guess this is the correct answer to that question.

Leave a Reply

Your email address will not be published.