NameError: name 'datetime' is not defined

PythonDatetime

Python Problem Overview


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
>>> 

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

It can also be used as below:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDoug FirView Question on Stackoverflow
Solution 1 - PythonSimeon VisserView Answer on Stackoverflow
Solution 2 - PythonSardar FaisalView Answer on Stackoverflow