Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NameError: name 'datetime' is not defined

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 >>>  
like image 343
Doug Fir Avatar asked Nov 12 '13 16:11

Doug Fir


People also ask

Why datetime is not defined?

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. Copied!

How do I fix NameError is not defined in Python?

The Python "NameError: function is not defined" occurs when we try to call a function that is not declared or before it is declared. To solve the error, make sure you haven't misspelled the function's name and call it after it has been declared.

How do I solve NameError?

The Python "NameError: name is not defined" occurs when we try to access a variable or function that is not defined or before it is defined. To solve the error, make sure you haven't misspelled the variable's name and access it after it has been declared.


2 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) 
like image 96
Simeon Visser Avatar answered Oct 05 '22 15:10

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) 
like image 26
Sardar Faisal Avatar answered Oct 05 '22 16:10

Sardar Faisal