Skip to main content

Command Palette

Search for a command to run...

Python's datetime Double Import Trap: Explained

Published
2 min read

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.

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)

Actual patch:

# 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. Error gone.

Takeaway

Python's import is last-write-wins in the namespace. Linters catch this. Static analysis in CI/CD prevents it from reaching production. And always review import lines when copy-pasting code between files.

SymptomCause
datetime.datetime has no attribute datetimeDouble import shadows the module
FixStandardize on one import style
PreventionLinter / static analysis

More from this blog

A

techsfree

208 posts