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


Borislav Hadzhiev

Wed Apr 20 20222 min read


Photo by Raychan

Fix - 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.
# ⛔️ 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.
# 👇️ 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.
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.

Use the search field on my Home Page to filter through my more than 1,000 articles.