This is a pretty simple error. Same code being run directly in the notebook cell (works) VS being defined in a function and then called in the cell (doesn't work)
If I run this code in the notebook, it works fine:
import datetime
now = datetime.datetime.now()
#other date stuff for later
today = datetime.datetime(now.year,now.month,now.day)
yesterday = datetime.date.today() - datetime.timedelta(1)
thisyear = datetime.datetime(now.year,1,1)
daynum = (today-thisyear).days
#print report date info
print('Report for the date: %s (day #%d)'%(yesterday,daynum))
print('Produced at: [%s]'%now)
however if I define a function with that code in another file (same folder), in a file called defs.py:
def currentdates():
import datetime
now = datetime.datetime.now()
#other date stuff for later
today = datetime.datetime(now.year,now.month,now.day)
yesterday = datetime.date.today() - datetime.timedelta(1)
thisyear = datetime.datetime(now.year,1,1)
daynum = (today-thisyear).days
return(now,today,yesterday,thisyear,daynum)
and then try to run it in the notebook, it doesn't work:
#setup dates
from defs import currentdates
from obspy import UTCDateTime
[now,today,yesterday,thisyear,daynum] = currentdates()
#print report date info
print('Report for the date: %s (day #%d)'%(yesterday,daynum))
print('Produced at: [%s]'%now)
This is the error I get:
NameError Traceback (most recent call last)
<ipython-input-15-d85dba8d0bba> in <module>()
5 from obspy import UTCDateTime
6
----> 7 [now,today,yesterday,thisyear,daynum] = currentdates()
8
9 #print report date info
/home/morgan/SPYDER/defs.py in currentdates()
57 daynum = (today-thisyear).days
58
---> 59 return(now,today,yesterday,thisyear,daynum)
60
61 print('..imported: currentdates() - outputs: [now,today,yesterday,thisyear,daynum]')
NameError: global name 'year' is not defined
I have looked at all the questions I can but they all have more complex issues as far as I can tell.
Other very similar questions I have seen and not been able to answer my question from (they generally seem to apply to 'circular referencing')
- Ipython notebook : Name error for Imported script function
- Functions NameError
- Python NameError: name is not defined
- NameErrors and functions in python
Botch-job solution
If I define: "year=2016" before I call the function, it works fine. Maybe the ipython notebook can't communicate with the calendar/clock on the computer? It shouldn't have to as the function is doing this surely? This sounds more like a bug than a code issue, maybe?