NameError: name 'datetime' is not defined

Question:

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
>>> 
Asked By: Doug Fir

||

Answers:

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)
Answered By: Simeon Visser

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)
Answered By: Sardar Faisal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.