When I typed in the following code it said that name 'now' is not defined. However, I did import datetime
?
from datetime import datetime
print str(now.month) + "/" + str(now.day) + "/" + str(now.year)
(I have already searched on the web for this but it did not come up with anything related to this)
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.
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 '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.
You haven't defined now
variable:
from datetime import datetime
now = datetime.now()
Also, to make a string from a datetime, use strftime():
Return a string representing the date, controlled by an explicit format string.
>>> from datetime import datetime
>>> now = datetime.now()
>>> now.strftime('%m/%d/%Y')
'09/15/2013'
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