Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Raychan
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
.
Here is an example of how the error occurs.
# ⛔️ 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.
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.
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.
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.
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.