Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
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
.
Here is an example of how the error occurs.
# ⛔️ 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.
# ✅ 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.
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.