Errors are inevitable, and one of them is nameerror: name ‘timedelta’ is not defined.
This error message is quite confusing and frustrating, especially if you’re new to this.
Well, you don’t have to worry because, in this article, we’ll help you to fix the name ‘timedelta’ is not defined.
What is “timedelta”?
The timedelta is an object that is part of Python’s datetime module that represents a duration or distinction between two points in time.
That allows users to perform calculations and manipulations on time intervals, such as adding or subtracting time, comparing durations, or converting time units.
Using “timedelta” makes it easier for the users to handle such as:
✔ Time-based calculations.
✔ Schedule events.
✔ Measures durations between different timestamps.
What is “nameerror name ‘timedelta’ is not defined”?
The namerror: name ‘timedelta’ is not defined error message occurs when you are trying to use the timedelta class, but you did not import it first.
Here’s the example scenario wherein you will encounter this error:
def calculate_time_difference(start_time, end_time):
duration = end_time - start_time
return duration
start_time = datetime.datetime(2022, 1, 1)
end_time = datetime.datetime(2023, 1, 2)
time_difference = calculate_time_difference(start_time, end_time)
print(time_difference)
If you try to run this code, as a result, it will throw an error message:
C:\Users\pies-pc2\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\pies-pc2\PycharmProjects\pythonProject\main.py
Traceback (most recent call last):
File "C:\Users\pies-pc2\PycharmProjects\pythonProject\main.py", line 5, in <module>
start_time = datetime.datetime(2022, 1, 1)
^^^^^^^^
NameError: name 'datetime' is not defined
This error message indicates that the Python interpreter cannot find the variable or function with the specified name. Specifically, in this case, the timedelta object from the datetime module is not accessible in your Python environment by default.
Why does the “name ‘timedelta’ is not defined” error occurs?
This error message can occur because of several reasons, such as:
❌ When the timedelta object is not imported from the datetime module.
❌ When there are typos in the function name.
❌ When you use it in incorrect scope.
How to fix the “nameerror: name ‘timedelta’ is not defined”?
To fix the nameerror name ‘timedelta’ is not defined error message, ensure that the timedelta object is imported from the datetime module before using it.
Solution 1: Import the timedelta
Import the timedelta object from the datetime module.
Here’s the solution for the example that we use above:
✅ from datetime import datetime, timedelta
def calculate_time_difference(start_time, end_time):
duration = end_time - start_time
return duration
start_time = datetime(2022, 1, 1)
end_time = datetime(2023, 2, 2)
time_difference = calculate_time_difference(start_time, end_time)
print(time_difference)
Output:
397 days, 0:00:00You can simply use the following code to import timedelta:
✅ from datetime import timedelta
You can also import the entire datetime module:
✅ import datetimeNote: Ensure that you imported timedelta is imported correctly from the datetime module.
The datetime module is in the Python standard library. However, you need to import it before using the module in your Python code.
Solution 2: Use the qualified name of the timedelta
Rather than importing the timedelta function from the datetime module, you can use its fully qualified name datetime.timedelta to access it.
import datetime
time_difference = datetime.timedelta(days=10)
print(time_difference)
Output:
10 days, 0:00:00Solution 3: Check for typos
Ensure that you have spelled timedelta correctly because it is one of the common mistakes of users that need to address.
Frequently Asked Questions(FAQs)
How to import the timedelta object?
You can import the timedelta object correctly by following the import statement below and putting it at the top or beginning of your code:
✅ from datetime import timedeltaI still getting the error after importing timedelta correctly, what should I do?
When you correctly imported the timedelta object, and still get this error message.
You must double-check if there are any typographical errors, ensure the correct scope, and verify the Python environment and package dependencies.
How to avoid NameError in Python code?
To avoid NameError in your Python code, ensure to import necessary modules, double-check variable names for to avoid typos, and ensure proper scoping.
Conclusion
The namerror: name ‘timedelta’ is not defined error message occurs when you are trying to use the timedelta class, but you did not import it first.
This article discusses what this error is all about and already provides different solutions to help you fix this error.
You could also check out other “nameerror” articles that may help you in the future if you encounter them.
- Nameerror: name ‘datetime’ is not defined
- Nameerror: name time is not defined
- Nameerror: name ‘sqlcontext’ is not defined
We are hoping that this article helps you fix the error. Thank you for reading itsourcecoders 😊
Function-related NameError
NameError on a function usually means the function was not defined yet, the wrong name was used, or the function is in a different scope.
Common triggers
- Function name typo.
caclulate()instead ofcalculate(). - Called before def. At module level.
- Function in wrong module. Imported from a different module than expected.
- Decorated function shadowed. Decorator returned wrong name.
Diagnostic pattern
# BAD — undefined function
def main():
result = compute_total() # NameError if compute_total not defined
main()
# GOOD — check spelling and scope
def compute_total():
return 42
def main():
result = compute_total()
print(result)
main()
# For decorated functions, make sure functools.wraps is used
from functools import wraps
def my_decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
return wrapper
Best practices
- Use editor autocomplete. Prevents most typo NameError.
- Order definitions before calls at module level.
- Use type hints. Editor flags undefined names immediately.
- Use functools.wraps in decorators to preserve the original function name.
Official documentation
Frequently Asked Questions
What is Python NameError and what causes it?
NameError is raised when Python encounters a name (variable, function, class) that hasn’t been defined in the current scope. Most common causes: typo in variable name, using a variable before assigning it, missing import, or referencing a variable that was defined inside a function but accessed outside it.
How do I fix ‘name X is not defined’?
Check three things: (1) Is the name a typo? Compare with the spelling where you defined it. (2) Did you import it? Add ‘from module import X’ or ‘import module’ at the top. (3) Is X defined in a different scope (inside a function, conditional branch, or with-block) that hasn’t executed yet at the point you’re using it? Move the definition before the use.
Why does my variable work in one cell but not another (Jupyter)?
Jupyter kernels keep state between cells. If you defined X in cell 5 and run cell 3 later, X exists. But after Kernel-Restart, only the cells you re-run define their variables. Always run cells top-to-bottom on a fresh kernel before submitting. Use ‘Restart and Run All’ to verify your notebook is reproducible.
What is the difference between NameError and AttributeError?
NameError: the name itself doesn’t exist anywhere in scope (typo, missing import, scope issue). AttributeError: the name exists and points to an object, but that object has no such attribute/method (typo on method name, wrong object type). NameError is about the variable; AttributeError is about what’s inside it.
Where can I find more NameError fixes?
Browse the NameError reference hub for 49+ specific fixes (NumPy, pandas, Jupyter, Python 2 to 3 migration). For Python scope rules see the Python Tutorial hub. For attribute-level errors see AttributeError.
