You're assigning some value to date
later in the function, wich caused Python to consider date
as a reference to the local variable instead of the imported module you expected
Rename this date
variable inside the function to solve the problem.
Pergunta
The following code (edited this based on the first answer):
time_difference_in_seconds = int(
(datetime.combine(date.today(), max_time)
- datetime.combine(date.today(), min_time)
).total_seconds())
[...]
for date in dates:
[...]
gives me this error:
UnboundLocalError: local variable 'date' referenced before assignment
Just to be clear, I have imported date and datetime from datetime. Moreover, when I execute the code in the werkzeug debugger, it works just fine and gives me the desired result:
[console ready]
>>> int((datetime.combine(date.today(), max_time)
- datetime.combine(date.today(), min_time)).total_seconds())
46800
In fact, I have used the same function in different views, and it doesn't cause any errors there.
What causes this strange error and how can I resolve it?
Solução
You're assigning some value to date
later in the function, wich caused Python to consider date
as a reference to the local variable instead of the imported module you expected
Rename this date
variable inside the function to solve the problem.
Outras dicas
I guess you must assign something to date
in your function like this:
def somefunc():
time_difference_in_seconds = int(
(datetime.combine(date.today(), max_time)
- datetime.combine(date.today(), min_time)
).total_seconds())
date = ...
renaming the variable will resolve this problem.