Reputation: 584
I have a very basic script that takes a piece of data as a CSV file, and converts the timestamps to whole hours. Part of this time conversion involves the package datetime, but the import of the package is not taken into the function that does the reformatting, and I have no idea why.
My code:
from datetime import datetime, timedelta
from dateutil import parser
import sys
def whole_hours(datafileloc, outfileloc):
whole_hour_data = {}
f = open(datafileloc, "r")
data = f.readlines()
f.close()
for line in data[1:]:
time = parser.parse(line.split(",")[0])
values = line.split(",")[1:]
if time.minute >= 30:
newtime = datetime(year=time.year, month=time.month, day=time.day, hour=time.hour, minute=0) + timedelta(hours=1)
else:
newtime = datetime(time.year, time.month, time.day, time.hour, 0)
if newtime not in whole_hour_data.keys():
whole_hour_data[newtime] = {"oldtime": time, "values": values}
else:
oldtime = whole_hour_data[newtime]["oldtime"]
if abs((time - newtime).total_seconds()) < abs((oldtime - newtime).total_seconds()):
whole_hour_data[newtime] = {"oldtime": time, "values": values}
with open(outfileloc, "w") as outfile:
outfile.write(data[0])
for datetime in sorted(whole_hour_data.keys()):
outfile.write("{datetime},{values}".format(datetime=datetime, values=",".join(whole_hour_data[datetime]["values"])))
whole_hours("C:/Users/<user>/Documents/test.csv", "C:/Users/<user>/Documents/output.csv")
When executing this script, I get the following error:
Traceback (most recent call last):
File "C:/Users/<user>/test.py", line 73, in <module>
whole_hours("C:/Users/<user>/Documents/test.csv", "C:/Users/<user>/Documents/output.csv")
File "C:/Users/<user>/test.py", line 54, in whole_hours
newtime = datetime(year=time.year, month=time.month, day=time.day, hour=time.hour, minute=0) + timedelta(hours=1)
UnboundLocalError: local variable 'datetime' referenced before assignment
Note I've masked my username :) I've figured out I can work around this error by using from datetime import datetime inside the function, or give the datetime package as a parameter for the function, but I am wondering why this needs to be done when the package is already imported at the start of the script. I've made several similar scripts that do not need this extra import.
Upvotes: 1
Views: 78
Reputation: 791
There is a section of code where you iterate values over a for loop here:
for datetime in sorted(whole_hour_data.keys()):
When you do this, I think that Python now sees datetime as a local variable and not a global import statement. You should change this variable name.
Upvotes: 3