def timetostr(timestamp):
time = time.localtime(timestamp)
datatime = time.strftime('%Y-%m-%d %H:%M:%S', time)
return datatime
报错:
Traceback (most recent call last):
File "E:\Py-Project\sample\main.py", line 18, in <module>
print("建立时间:", timetostr(fileinfo.st_ctime))
File "E:\Py-Project\sample\main.py", line 6, in timetostr
time = time.localtime(timestamp)
UnboundLocalError: local variable 'time' referenced before assignment
也就是:赋值前引用的局部变量“time”
解决方法:修改变量名:
def timetostr(timestamp):
loctime = time.localtime(timestamp)
datatime = time.strftime('%Y-%m-%d %H:%M:%S', loctime)
return datatime
文章讲述了在Python代码中,由于尝试在函数定义前引用`time`变量导致的`UnboundLocalError`,并给出了修正方法,即在调用`time.localtime()`之前先定义`loctime`。
3142





