Fix - NameError: name 'timedelta' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

Fix - NameError: name 'timedelta' is not defined in Python #

The Python "NameError: name 'timedelta' is not defined" occurs when we use the timedelta class without importing it first. To solve the error, import the timedelta class before using it - from datetime import timedelta.

nameerror name timedelta is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ NameError: name 'timedelta' is not defined delta = timedelta( days=30, seconds=45, microseconds=10, milliseconds=29000, minutes=3, hours=7, weeks=2, ) print(delta) print(delta.max) print(delta.min)

To solve the error, we have to import the timedelta class from the datetime module.

main.py
# ✅ import timedelta class first from datetime import timedelta delta = timedelta( days=30, seconds=45, microseconds=10, milliseconds=29000, minutes=3, hours=7, weeks=2, ) print(delta) print(delta.max) print(delta.min)

Even though the datetime module is in the Python standard library, we still have to import it before using it.

Make sure you haven't misspelled timedelta in the import statement as names of classes are case-sensitive.

Also, make sure you haven't imported timedelta in a nested scope, e.g. a function. Import the function at the top level to be able to use it throughout your code.

A timedelta object represents a duration - the difference between two dates or times.

All of the arguments we passed to the class in the example above are optional and default to 0.

You can read more about timedelta objects by visiting the official docs.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.