The error AttributeError: Type Object ‘Datetime.Datetime’ Has No Attribute ‘Datetime’ happens when imports and datetime usage do not match in code.
AttributeError: Type Object ‘Datetime.Datetime’ Has No Attribute ‘Datetime’
This message looks intimidating, especially if it pops up while you are under time pressure with a Python script. The full text usually reads AttributeError: type object 'datetime.datetime' has no attribute 'datetime', and it signals that Python is trying to reach an attribute that does not exist on the datetime type.
In plain terms, Python thinks datetime is a type from the datetime module, not an instance or the module itself, and you are asking for .datetime on that type again. Once you see how the module and class are laid out, the message starts to make sense and becomes straightforward to correct.
The good news is that this issue comes from a small mismatch between imports and usage. Once you adjust a line or two, your script goes back to printing timestamps or calculating time ranges without drama.
You might meet this message while running a one off utility script, a long lived web app, or a short experiment in a Jupyter notebook. The stack trace can look loud, yet the root sits near the top of the file where the import lives, not deep inside third party code.
- Console Scripts — Short tools run from the command line often mix quick edits with copy pasted imports, which makes this datetime issue pop up after small changes.
- Web Applications — Django or Flask projects with many modules can pick up mixed import styles when several people touch the same file across months.
- Data Notebooks — Interactive notebooks rerun cells out of order, so a later cell might reuse
datetimein a way that no longer matches the original import.
Why This Datetime Attributeerror Happens In Python
To understand the root cause, it helps to recall how the datetime module is structured. The module is called datetime, and inside that module there is a class that is also called datetime. Many tutorials show imports such as from datetime import datetime, which can blur that mental model.
When the interpreter raises the message AttributeError: type object 'datetime.datetime' has no attribute 'datetime', it usually means your code imported the module one way and then tried to call it as if you had imported it another way. That mismatch leads Python to treat datetime.datetime as a type that does not contain another datetime attribute inside it.
Several patterns in day to day code lead to this state. You might reassign the name datetime to something else, import symbols in two different ways in the same file, or rely on autocomplete, which then inserts a call that does not match your import style.
A handy way to picture the layout is to treat datetime as a file and datetime.datetime as a class inside that file. When you import at the module level, you gain names such as datetime.timedelta and datetime.date as well, which matters once the script grows beyond a single timestamp.
Fixing The ‘type object datetime.datetime has no attribute datetime’ Error Step By Step
Once you know the patterns that confuse the interpreter, you can fix them in a repeatable way. The checklist below walks through the most common adjustments that clear the error in real projects.
- Check How You Import Datetime — Scan the top of your file for lines such as
import datetimeorfrom datetime import datetime. Make sure you pick one clear style instead of mixing both in the same module. - Match Usage To The Import Style — If you use
import datetime, then create objects withdatetime.datetime(...). If you usefrom datetime import datetime, then create objects withdatetime(...)instead. - Remove Conflicting Reassignments — Check for lines where you accidentally set
datetime = datetime.datetimeor reuse the namedatetimefor something like a string. Remove or rename those variables so the original import stays intact. - Search For Shadowed Imports — If your project has many files, confirm that each one follows a clear pattern. A stray
from datetime import datetime as dtor a local function argument nameddatetimecan shadow the module in subtle ways. - Restart Your Interpreter Session — In notebooks and shells, stale variables linger between runs. Restart the session to clear reassignments that might hide the real module or class.
Apply these steps patiently, from import inspection through to session restart. In most cases, the attributeerror clears up once imports and usage line up cleanly.
Common Code Patterns That Trigger The Datetime Attributeerror
The surface message looks the same, but the source can vary. Walking through typical patterns helps you spot the issue in your own script without guesswork.
Mixing Import Styles In One File
A frequent source of trouble appears when one file mixes import datetime with from datetime import datetime. That pattern invites confusion around which name points to the module and which name points to the class.
import datetime
from datetime import datetime
now = datetime.datetime.now()
In this sample, the call datetime.datetime.now() might look fine at first glance, yet the second import changed what datetime means. Depending on the order of imports and edits, the name can now point to the class, so the extra .datetime layer no longer exists.
Rebinding The Datetime Name
Another pattern shows up when the code reuses datetime as a local variable, function argument, or class property. Once you assign a new value to that name, Python loses the link to the original module or class.
from datetime import datetime
datetime = "2024-01-01"
start = datetime.datetime.now()
Here the string assignment hides the imported class. When the interpreter reaches datetime.datetime, it now tries to call an attribute on a string value, which fails with an attributeerror.
Using Autocomplete Without Checking Imports
Developer tools often suggest datetime.datetime as soon as you type datetime. If the file only imported from datetime import datetime, that suggestion no longer fits. The editor does not always know how you plan to structure imports, so a quick glance at suggestions before accepting them can save time.
Misplaced Imports In Package Layouts
Larger code bases sometimes move imports into functions or methods to speed up startup or avoid circular references. When a function then assigns to datetime in a local scope, later calls that expect datetime.datetime can face the attributeerror only under certain paths.
If the message appears only in production or only under specific feature flags, look for imports that sit inside functions, methods, or blocks. Lifting the datetime import back to the top level, or choosing a distinct alias in that narrow scope, often clears puzzling reports.
Safer Ways To Work With Python Datetime
Once you fix the immediate error, you can reduce the chance of seeing it again by settling on habits that keep names clear. Small shifts in style go a long way in busy projects.
- Pick One Import Pattern Per Project — Decide whether your team prefers
import datetimeorfrom datetime import datetime, then stick with that decision across files so names stay predictable. - Use Aliases For Clarity — When you need both the module and the class, use aliases such as
import datetime as datetime_moduleandfrom datetime import datetime as DatetimeClass. That phrasing keeps each role distinct. - Avoid Reusing The Datetime Name — Choose descriptive variable names such as
start_timeorrun_atinstead of shadowing the module with short generic names. - Add Type Hints — When you use type hints, mismatched names show up sooner in editors and continuous checks, which cuts down on confusing runtime errors.
- Run A Linter Or Static Checker — Tools such as mypy or other static analyzers can flag shadowed names and unused imports, which points straight at spots where
datetimelost its original meaning.
These habits keep the line between module, class, and instances sharp. Clear naming also helps later refactors, since you can search for a specific alias instead of a crowded generic name.
Quick Reference Table For Datetime Import Patterns
A short reference table can make fixes faster when you run into this attributeerror in new code. Match your goal in the left column, then apply the suggested import and usage pair.
| Goal | Import | Usage |
|---|---|---|
| Create a datetime object | import datetime |
dt = datetime.datetime.now() |
| Create a datetime object with direct class name | from datetime import datetime |
dt = datetime.now() |
| Use both module and class clearly | import datetime as datetime_module |
dt = DatetimeClass.now() |
Pin this pattern in your mind, and the message AttributeError: type object 'datetime.datetime' has no attribute 'datetime' turns into a quick hint rather than a roadblock.
When teammates swap between these styles, paste a small copy of this table into your project docs or README. Shared reference material keeps everyone reaching for the same patterns, which trims down scattered fixes and surprise errors during reviews.
Putting The Fix Into A Real Script
After walking through causes and fixes, it helps to see a final working pattern. Start with a broken script, then apply the small edits that line imports up with usage.
# Broken version
import datetime
from datetime import datetime
run_at = datetime.datetime(2024, 1, 1, 9, 0)
print(run_at)
This mix of imports can raise the attributeerror once edits shuffle the order or a tool rewrites imports at the top of the file. A safer version picks one style and uses it consistently.
- Where Does Datetime Come From Here — Read the nearest imports and assignments so you know whether
datetimerefers to the module, the class, or a local variable. - When Did The Error Start — Check recent commits or cell changes; a single new import line or renamed variable often lines up with the first stack trace.
- Is The Session Clean — In shells and notebooks, restart the process so old values do not hide the original
datetimeimport.
# Fixed version using module and class names
import datetime
run_at = datetime.datetime(2024, 1, 1, 9, 0)
print(run_at)
You can flip the style if you prefer the shorter call form. The key is that imports and calls line up so that datetime points to the module or the class in a predictable way.
# Fixed version using plain class name
from datetime import datetime
run_at = datetime(2024, 1, 1, 9, 0)
print(run_at)
Once you shift habits in this direction, the string AttributeError: Type Object 'Datetime.Datetime' Has No Attribute 'Datetime' becomes familiar. Instead of pausing your workday, it nudges you to glance at imports, clean them up, and move on.
