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:
|
|
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:
|
|
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:
|
|
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()
.