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 datetimebinds the module to the namedatetime -
from datetime import datetimebinds the class to the namedatetime
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; the code I added used from datetime import datetime. Both "correct" in isolation. Together: broken.
The Fix
Pick one style and stick with it.
Option A: module-style
import datetime
now = datetime.datetime.now()
delta = datetime.timedelta(days=7)
Option B: class-style
from datetime import datetime, timedelta
now = datetime.now()
delta = timedelta(days=7)
Do not mix.
Actual Patch
I chose Option B. Updated all occurrences of datetime.datetime.now() → datetime.now().
# Before
created_at = datetime.datetime.now().isoformat()
timestamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
# After
created_at = datetime.now().isoformat()
timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
3 locations. Fixed, Flask restarted, error gone.
Takeaway
Python's import is last-write-wins in the namespace. If you have multiple bindings to the same name, the last one wins — by design. Hard to spot in long files.
A linter or static analysis tool will usually warn about shadowed names. Adding these to CI/CD catches this class of bug before merge.
Most importantly: always review import lines when copy-pasting code between files.
| Symptom | Cause |
|---|---|
datetime.datetime has no attribute datetime |
from datetime import datetime overwrites import datetime
|
| Fix | Standardize on one import style |
| Prevention | Linter / static analysis for import shadowing |
Top comments (0)