How to Solve Python NameError: name ‘datetime’ is not defined

by | Programming, Python, Tips

This error occurs when you try to use the datetime module without importing it first. You can solve this error by importing the module. For example,

import datetime

print(datetime.date.today())

This tutorial will go through how to solve the error with code examples.


NameError: name ‘datetime’ is not defined

Python raises the NameError when it cannot recognise a name in our program. In other words, the name we are trying to use is not defined in the local or global scope. A name can be related to a built-in function, module, or something we define in our programs, like a variable or a function.

The error typically arises when:

  • We misspell a name
  • We do not define a variable or function
  • We do not import a module

In this tutorial, the source of the error NameError: name ‘datetime’ is not defined is usually due to not importing the module. Let’s look at an example.

Example

The datetime module provides classes for manipulating dates and times.

The datetime module is built-in, which means it comes with Python.

Let’s look at an example of using the date class and its today() method to get today’s date:

print(datetime.date.today())

Let’s run the code to see what happens:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [1], in <cell line: 1>()
----> 1 print(datetime.date.today())

NameError: name 'datetime' is not defined

The error occurred because we did not import the datetime module. Although datetime is a built-in module, we still need to import it.

Solution #1: Import datetime

We can import the module by putting an import statement at the top of the program. Let’s look at the updated code:

import datetime

print(datetime.date.today())

Let’s run the code to get today’s date:

2022-06-13

Solution #2: Use from keyword

We can also use the from keyword to import a specific variable, class or function from a module. In this case, we want to import the date class from the datetime module.

Using the from keyword means we do not have to specify the datetime module in the rest of the program, we only need the date class.

Let’s look at the updated code:

from datetime import date

print(date.today())

Let’s run the code to get today’s date:

2022-06-13

The from keyword is also useful for importing multiple classes, functions or variables from a module. Let’s look at an example of importing the datetime and timedelta classes from the datetime module.

from datetime import datetime, timedelta

# Current datetime
now = datetime.now()
 
# printing initial_date
print ('initial datetime:', now)
 
# Datetime two years before now
past = now - timedelta(days = 730)

print('date two years from initial datetime: ', past)

In the above code, we use the now() method from the datetime class to create a datetime object that represents the current date and time. Then, we use timedelta to find the date and time two years before the current date and time. Let’s run the code to see the result:

initial datetime: 2022-06-13 23:28:49.530895
date two years from initial datetime:  2020-06-13 23:28:49.530895

Summary

Congratulations on reading to the end of this tutorial!

For further reading on NameErrors, go to the articles:

To learn more about Python for data science and machine learning, go to the online courses page on Python for the most comprehensive courses available.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨