You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 07:27:53