mavngoose
mavngoose

Reputation: 1

Using time.time() in Python - errors don't seem to make sense

Using time.time() as a means to schedule a task easily, but for some reason, I keep getting an error which doesn't make a lot of sense to me. I printed timenow and it reads correctly.
Code:

 timenow = time.time()
    def my_BidAsk(msg):
        global timenow
        tnow = time.time()
        if (tnow - timenow) >= 60:
            resample()
            timenow = time.time()

Here is the error I get, but it doesn't make sense because whether I predefine it or not, globally or locally, the error is still the same. Any idea why?

06-Dec-16 01:09:18 ERROR     Exception in message dispatch.  Handler 'my_BidAsk' for 'tickPrice'
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/ib/opt/dispatcher.py", line 44, in __call__
    results.append(listener(message))
  File "/Users/usr/Desktop/Hobbies/Coding/connect-contract-order IB.py", line 57, in my_BidAsk
    tnow = time.time()
UnboundLocalError: local variable 'time' referenced before assignment

Upvotes: 0

Views: 901

Answers (1)

Anil Patel
Anil Patel

Reputation: 21

I had a similar issue which I was able to resolve. In my case, I had a local variable called "time" initialized later in the same function. Using the name of a library as a local variable name causes the exception to be raised when the script runs "t_start = time.time()".

To solve this, I renamed my local variable from "time" to something unoffending (in my case, "time_s"). Ignore any bad pandas practices...

t_start = time.time()

for index, row in profile.iterrows():
    time = row['time_s']
    current = row['Current']
    voltage = row['Voltage_V']
    soc = row['SOC']

changed to:

t_start = time.time()

for index, row in profile.iterrows():
    time_s = row['time_s']
    current = row['Current']
    voltage = row['Voltage_V']
    soc = row['SOC']

Upvotes: 2

Related Questions