python - 如何从 MySQL 日期时间转换为 numpy datetime64?

标签 python mysql django numpy

我正在将游标加载到 numpy 数组中,作为使用 pyplot 的先驱。

我没有成功将日期时间字段从 Mysql 转换为 numpy 使用的 datetime64。

Python代码

@login_required
def resource(request, resource_id):
    cnxn = pyodbc.connect(SOLAR_SECURED_CONNECTION)
    cursor = cnxn.cursor()

    sqlstr = """select r.name as resource_name, rm.mobile_id_id, fd.value, pd.update_time, rt.capacity
                    from asset_monitor_resource r, asset_monitor_formulateddata fd, asset_monitor_resourcetype rt,
                         asset_monitor_parseddata pd, asset_monitor_resourcemapping rm
                    where r.id = rm.resource_id_id and
                          r.id = fd.resource_id_id and
                          fd.rawdata_id_Id = pd.rawdata_id_id and
                          r.resource_type_id_id = rt.id and
                          r.id = ?
                    order by pd.update_time desc"""

    cursor.execute(sqlstr, resource_id)

    data_type = [('resource_name', np.str, 100),
                          ('mobile_id_id', np.int8),
                          ('value', np.float),
                          ('update_time', np.datetime64),
                          ('capacity', np.int8)]

    r_rows = cursor.fetchall()
    for r in r_rows:
        dt = r.update_time
        r.update_time = np.datetime64(dt).astype(datetime)

    narray = np.fromiter((tuple(row) for row in r_rows), dtype=data_type)

    print 'narray='+str(narray)

    dateplot(narray, resource_id)
    image_file = "tempfig"+str(resource_id)+".png"

    return render_to_response('resource.html', {'data': r_rows, 'resource_id': resource_id, 'image_file': image_file}, context_instance=RequestContext(request))

回溯

[Tue Dec 03 10:56:45 2013] [error] Internal Server Error: /user/resource/113/
[Tue Dec 03 10:56:45 2013] [error] Traceback (most recent call last):
[Tue Dec 03 10:56:45 2013] [error]   File "C:\\Python27\\Lib\\site-packages\\django\\core\\handlers\\base.py", line 115, in get_response
[Tue Dec 03 10:56:45 2013] [error]     response = callback(request, *callback_args, **callback_kwargs)
[Tue Dec 03 10:56:45 2013] [error]   File "C:\\Python27\\Lib\\site-packages\\django\\contrib\\auth\\decorators.py", line 25, in _wrapped_view
[Tue Dec 03 10:56:45 2013] [error]     return view_func(request, *args, **kwargs)
[Tue Dec 03 10:56:45 2013] [error]   File "C:\\dev\\solar_secured\\asset_monitor\\views.py", line 319, in resource
[Tue Dec 03 10:56:45 2013] [error]     narray = np.fromiter((tuple(row) for row in r_rows), dtype=data_type)
[Tue Dec 03 10:56:45 2013] [error] TypeError: Cannot cast datetime.datetime object from metadata [us] to  according to the rule 'same_kind'

最佳答案

您可以在日期时间数据类型中使用明确的单位规范:

import datetime

row = ['resource', 1, 1.1, datetime.now(), 10]
r_rows = [row]

data_type = [('resource_name', np.str, 100),
             ('mobile_id_id', np.int8),
             ('value', np.float),
             ('update_time', '<M8[us]'),
             ('capacity', np.int8)]

narray = np.fromiter((tuple(row) for row in r_rows), dtype=data_type)

结果

>>> narray['update_time'][0]
numpy.datetime64('2013-12-03T16:27:05.456766+0000')

关于python - 如何从 MySQL 日期时间转换为 numpy datetime64?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20355495/

相关文章:

django - 在 Django 中向表单动态添加新字段

python - 如何以最直接的方式在全局范围内使用 matplotlib 中的任何系统字体?

mysql - 使用不同的 MySQL 数据库引擎

mysql - MYSQL中递归存储过程获取分层数据的表现

javascript - 如何为模板中显示的 django 对象生成唯一的 div id

python - 从 appengine 迁移到完整的 django 的下一步是什么?

python - Django如何为模型属性自动生成唯一的数字/字符串

python - Elasticsearch : pyes. 异常。IndexMissing Exception 搜索结果异常

python - 继承烦恼。 - Python

php - 基于日期时间mysql创建html select