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 >>>
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!
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.
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.
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)
It can also be used as below:
from datetime import datetime start_date = datetime(2016,3,1) end_date = datetime(2016,3,10)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With