python - 将包含日期时间对象的元组转换为 numpy 结构化数组时出现 `TypeError: float() argument must be a string or a number`

标签 python mysql datetime numpy

我试图使用来自 MySQL 的数据在 Python 中绘制图表,但出现以下错误:

File "mygraph.py", line 45, in <module>
    Raw = numpy.fromiter(cursor.fetchall(), count=-1, dtype=[('', numpy.float)]*3)
TypeError: float() argument must be a string or a number

日期使用datetime 格式保存在数据库中。以下是我的代码的一部分:

cursor = DBconn.cursor()
sql = "select mydate,temp,hum from temptable where unix_timestamp(mydate) >= (unix_timestamp(now())-(60*60*24))"
cursor.execute(sql)
Raw = numpy.fromiter(cursor.fetchall(), count=-1, dtype=[('', numpy.float)]*3)
Raw = Raw.view(numpy.float).reshape(-1, 3)
(samples,ports)=Raw.shape
print 'Samples: {}, DataPoints: {}'.format(samples,ports),
plotme=numpy.zeros((samples,ports-1)) # make an array the same shape minus the epoch numbers

问题可能出在日期格式上,例如我保存在 datetime 中,但我使用纪元调用?谁能指导我如何解决这个问题?

更新:cursor.fetchall() 打印以下内容:

((datetime.datetime(2015, 7, 24, 21, 2, 1), Decimal('21.4'), Decimal('60.9')))

最佳答案

您在调用 np.fromiter 时指定的数据类型与 cursor.fetchall() 返回的元组列表的相应类型不匹配。每个元组中的第一项是 datetime.datetime,但您的 dtype 由所有 float 组成。由于没有安全的方法将 datetime.datetime 转换为 float ,因此您会收到 TypeError

尝试创建第一个字段 numpy.datetime64而不是 float :

numpy.fromiter(cursor.fetchall(), count=-1,
               dtype=zip(('',) * 3, ('M8[us]', '<f8', '<f8'))))

关于python - 将包含日期时间对象的元组转换为 numpy 结构化数组时出现 `TypeError: float() argument must be a string or a number`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31626691/

相关文章:

python - 尝试查找与数组中的项目相对应的项目

python - 如何在 Django Rest Framework 中将 has_object_permission 与 APIView 一起使用?

php - 我应该如何设计 PHP 中 SQL 列生成器的接口(interface)?

php - 如何检测 Android 应用程序的卸载并从服务器中删除相关用户的数据?

python - Django 'if and' 模板

python - 在while循环中如何使用while循环

c# - 循环 SQL 查询的正确方法?

php - 如何处理 PHP + MySQL timezones 和 MySQL GROUP BY [date] 查询?

java - 使用 JAVA 中的日期类处理时区更改

python - DateTimeField 收到一个天真的日期时间