Python Error – AttributeError: type object ‘datetime.datetime’ has no attribute ‘datetime’ (2 Examples)
In this tutorial, I’ll illustrate how to deal with the AttributeError: type object ‘datetime.datetime’ has no attribute ‘datetime’ in Python programming.
Example 1: Replicating the Error Message – AttributeError: type object ‘datetime.datetime’ has no attribute ‘datetime’
To reproduce the error message, we have to load the datetime module as you can see below:
from datetime import datetime # Load datetime |
from datetime import datetime # Load datetime
If we afterwards want to work with the datetime function, we get the following output:
date_x1 = datetime.datetime(2018, 2, 7) # Trying to apply datetime function # AttributeError: type object 'datetime.datetime' has no attribute 'datetime' |
date_x1 = datetime.datetime(2018, 2, 7) # Trying to apply datetime function # AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
Example 2: Fixing the Error Message – AttributeError: type object ‘datetime.datetime’ has no attribute ‘datetime’
To fix the problem, we have to use “import datetime” instead of “from datetime import datetime”:
import datetime # Load datetime module |
import datetime # Load datetime module
Now we can properly use the datetime function.
date_x1 = datetime.datetime(2018, 2, 7) # Application of datetime function works fine print(date_x1) # 2018-02-07 00:00:00 |
date_x1 = datetime.datetime(2018, 2, 7) # Application of datetime function works fine print(date_x1) # 2018-02-07 00:00:00
Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.