NameError: name 'time' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

NameError: name 'time' is not defined in Python #

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

nameerror name time is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ NameError: name 'time' is not defined time.sleep(1) print( time.strftime( "%a, %d %b %Y %H:%M:%S +0000", time.gmtime() ) )

To solve the error, we have to import the time module.

main.py
# 👇️ first import time module import time time.sleep(1) print( time.strftime( "%a, %d %b %Y %H:%M:%S +0000", time.gmtime() ) )

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

Make sure you haven't used a capital letter t when importing time because module names are case-sensitive.

Alternatively, you can make your code a little more concise by only importing the functions that you use in your code.

main.py
from time import sleep, strftime, gmtime sleep(1) print( strftime( "%a, %d %b %Y %H:%M:%S +0000", gmtime() ) )

The example shows how to import the sleep() and strftime() and gmtime functions from the time module.

Instead of accessing the members on the module, e.g. time.sleep(), we now access them directly.

This should be your preferred approach because it makes your code easier to read.

For example, when we use an import such as import time, it is much harder to see which functions from the time module are being used in the file.

Conversely, when we import specific functions, it is much easier to see which functions from the time module are being used.

The time module provides many time-related functions.

You can view all of the functions and constants the time module provides by visiting the official docs.

Conclusion #

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

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.