79

I'm teaching myself Python and was just "exploring". Google says that datetime is a global variable but when I try to find todays date in the terminal I receive the NameError in the question title?

mynames-MacBook:pythonhard myname$ python
Enthought Canopy Python 2.7.3 | 64-bit | (default, Aug  8 2013, 05:37:06) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> date = datetime.date.today()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'datetime' is not defined
>>> 
1
  • 3
    Where does it say that datetime is a global variable, exactly? Commented Nov 12, 2013 at 16:15

3 Answers 3

142

You need to import the module datetime first:

>>> import datetime

After that it works:

>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)
Sign up to request clarification or add additional context in comments.

1 Comment

This is not about common variables, this is about importing modules from the Python Standard Library: docs.python.org/2/library/index.html . You generally only import what you need, not everything.
7

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

Comments

0

I encountered the same issue while working on my Django project, and the solution was very simple. I did an import, as shown below. This is usually done on top of the file. For future reference, I hope this helps.

from datetime import datetime

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.