1

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.

asked Dec 29, 2017 at 14:54
1
  • 1
    You've used datetime in your iterator, and that overwrites the import statement. That could cause a problem, but I'm not sure if it solves it for you. Commented Dec 29, 2017 at 15:06

1 Answer 1

3

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.

answered Dec 29, 2017 at 15:09
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I can't believe I was that stupid... Thanks alot, that solved my problem! Still not clear why an extra import statement in the function would solve that though.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.