简体   繁体   English

Python包导入没有进入功能

[英]Python package import not taken into function

I have a very basic script that takes a piece of data as a CSV file, and converts the timestamps to whole hours. 我有一个非常基本的脚本,它将一段数据作为CSV文件,并将时间戳转换为整个小时。 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. 注意我已经掩盖了我的用户名:)我已经想通过在函数内部使用datetime import datetime来解决这个错误,或者给datetime包作为函数的参数,但是我想知道为什么这需要在脚本开始时已导入包时完成。 I've made several similar scripts that do not need this extra import. 我已经制作了几个不需要额外导入的类似脚本。

There is a section of code where you iterate values over a for loop here: 有一段代码可以在这里通过for循环迭代值:

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. 当你这样做时,我认为Python现在将datetime视为局部变量而不是全局import语句。 You should change this variable name. 您应该更改此变量名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM