AttributeError: module ‘datetime’ has no attribute ‘strptime’ error typically occurs when you try to access the strptime() method directly on the datetime module instead of datetime class inside it.
To fix the error, you can call the method on the datetime class inside the datetime module or import the class datetime directly.
Here are two ways to import the datetime class correctly:
First way
import datetime
datetime.datetime.strptime()
Second way
from datetime import datetime
datetime.strptime()
Flowchart
Reproduce the error
import datetime
date_string = "2022-10-23"
format_string = "%Y-%m-%d"
print(datetime.strptime(date_string, format_string))
Output
AttributeError: module 'datetime' has no attribute 'strptime'
How to fix it?
Solution 1: Call the method on the class datetime
import datetime
date_string = "2023-01-29"
format_string = "%Y-%m-%d"
print(datetime.datetime.strptime(date_string, format_string))
Output
2023-01-29 00:00:00
Solution 2: Import the class datetime directly
Alternatively, you can import the datetime module like this: “from datetime import datetime”. You import the datetime class directly instead of the datetime module.
from datetime import datetime
date_string = "2023-01-29"
format_string = "%Y-%m-%d"
print(datetime.strptime(date_string, format_string))
Output
2023-01-29 00:00:00
That’s it.