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

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Raychan

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

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

nameerror name datetime is not defined

Here is an example of how the error occurs.

main.py
# ⛔️ NameError: name 'datetime' is not defined print(datetime.date.today()) d = datetime.date(2022, 9, 24) print(d) t = datetime.time(9, 30) print(t)

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

main.py
import datetime print(datetime.date.today()) d = datetime.date(2022, 9, 24) print(d) # 👉️ "2022-09-24" t = datetime.time(9, 30) print(t) # 👉️ 09:30:00

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 used a capital letter d when importing datetime because module names are case-sensitive.

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

main.py
from datetime import date, time print(date.today()) d = date(2022, 9, 24) print(d) # "2022-09-24" t = time(9, 30) print(t) # 👉️ 09:30:00

The example shows how to import the date() and time() classes from the datetime module.

Instead of accessing the members on the module, e.g. datetime.date(), 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 datetime, it is much harder to see which classes from the datetime module are being used in the file.

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

The datetime module provides classes for manipulating dates and times.

You can view all of the classes and constants the datetime module provides by visiting the official docs.

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