Python API解析数据库数据时报错:datetime.datetime无__round__方法
解决TypeError: datetime.datetime没有__round__方法的问题
你遇到的问题是索引顺序搞反了,导致round()意外作用在了datetime类型的数据上。
看你的代码,循环变量i遍历的是histTuple的行索引,但你在取温度和湿度时用了histTuple[0][i]和histTuple[1][i]——这相当于取第0行的第i个元素、第1行的第i个元素。如果histTuple的结构是每行包含(温度, 湿度, 时间),那么当i=2时,histTuple[0][2]就是第一行的时间字段(datetime类型),对它执行round()自然会触发这个错误。
正确的做法是按行索引在前,字段索引在后的方式取值:histTuple[i][0]是第i行的温度,histTuple[i][1]是第i行的湿度。
修正后的代码
response = [] for i in range(len(histTuple)): currentTime = histTuple[i][2].replace(microsecond=0) currentTime = str(currentTime) + f" GMT{TIMEZONE}" response.append({ "humidity": round(histTuple[i][1], 1), "celsius": round(histTuple[i][0]), "fahrenheit": round(histTuple[i][0] * 9/5 + 32), "timestamp": currentTime })
更优雅的写法(直接遍历行)
可以不用索引,直接解构每行的数据,彻底避免索引错误:
response = [] for temp, hum, dt in histTuple: currentTime = dt.replace(microsecond=0) currentTime = str(currentTime) + f" GMT{TIMEZONE}" response.append({ "humidity": round(hum, 1), "celsius": round(temp), "fahrenheit": round(temp * 9/5 + 32), "timestamp": currentTime })
内容的提问来源于stack exchange,提问作者berriz44
相关产品推荐
相关产品推荐

