
Python's datetime Double Import Trap: 'type object datetime.datetime has no attribute datetime'
While adding code to a Flask API server, I suddenly hit this error: AttributeError: type object 'datetime.datetime' has no attribute 'datetime' My code looked like this: datetime . datetime . now () Nothing obviously wrong. But Python said "no such attribute." What Was Happening The real issue was at the top of the file: import datetime from datetime import datetime These two lines coexist. Here's the problem: import datetime binds the module to the name datetime from datetime import datetime binds the class to the name datetime The second import overwrites the first. Now datetime refers to the class, not the module. When you call datetime.datetime.now() , Python looks for a datetime attribute on the datetime class — which doesn't exist. Hence the error. Why It's Easy to Miss When files grow long, you stop checking import lines. When copy-pasting code from other files, you bring imports along too. The collision stays hidden until runtime. In my case: original code used import datetime
Continue reading on Dev.to Python
Opens in a new tab



