Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Name 'now' is not defined?

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)

like image 998
ComputerXplorer Avatar asked Sep 14 '13 20:09

ComputerXplorer


People also ask

What does name is not defined mean?

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.

What do you do when Python says not defined?

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.

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.


1 Answers

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'
like image 146
alecxe Avatar answered Sep 20 '22 19:09

alecxe