如何将日期时间插入到Cassandra 1.2时间戳列中

Ser*_*rán 10 python cql cassandra

重要事项 如果您今天正在处理此问题,请使用datastax中的新cassandra-driver(即import cassandra),因为它解决了大多数常见问题,并且不再使用旧的cql驱动程序,它已经过时了!这个问题从新驱动程序甚至开发之前就已经过时了,我们不得不使用一个名为cql的不完整的旧库(import cql < - 不再使用它,转移到新的驱动程序).

介绍 我正在使用python库cql来访问Cassandra 1.2数据库.在数据库中,我有一个带有timestamp列的表,在我的Python代码中,我有一个要插入列的日期时间.示例如下:

CREATE TABLE test (
     id text PRIMARY KEY,
     last_sent timestamp
);
Run Code Online (Sandbox Code Playgroud)

代码

import cql
import datetime
...
cql_statement = "update test set last_sent = :last_sent where id =:id"
rename_dict = {}
rename_dict['id'] = 'someid'
rename_dict['last_sent'] = datetime.datetime.now()
cursor.execute (cql_statement, rename_dict)
Run Code Online (Sandbox Code Playgroud)

问题

当我执行代码时,执行的实际cql语句是这样的:

update test set last_sent =2013-05-13 15:12:51 where id = 'someid'
Run Code Online (Sandbox Code Playgroud)

然后它失败并出现错误

 Bad Request: line 1:XX missing EOF at '-05'
Run Code Online (Sandbox Code Playgroud)

问题似乎是cql库没有转义('')或在运行查询之前转换日期时间.

问题 如果没有手动转义日期并且能够将更精确的完整时间戳存储到cassandra时间戳列中,这样做的正确方法是什么?

提前致谢!

abh*_*bhi 10

我可以告诉你如何在cqlsh中做到这一点.试试这个

update test set last_sent =1368438171000 where id = 'someid'
Run Code Online (Sandbox Code Playgroud)

日期时间的等价长值2013-05-13 15:12:511368438171000


Ser*_*rán 7

abhi已经声明这可以使用毫秒来创建,因为epoch是来自cqlsh的长值,现在我们需要使它在Python代码中工作.

当使用cql库时,这种转换(从日期时间到epoch之后的毫秒)不会发生,所以为了使更新工作并且仍然具有将日期时间转换为自纪元以来的毫秒数所需的精度.

来源 使用这个有用的问题:从datetime开始获取millis,特别是这个函数(请注意我所做的一点改动):

解决方案

import datetime

def unix_time(dt):
    epoch = datetime.datetime.utcfromtimestamp(0)
    delta = dt - epoch
    return delta.total_seconds()

def unix_time_millis(dt):
    return long(unix_time(dt) * 1000.0)
Run Code Online (Sandbox Code Playgroud)

对于此示例,代码将是:

cql_statement = "update test set last_sent = :last_sent where id =:id"
rename_dict = {}
rename_dict['id'] = 'someid'
rename_dict['last_sent'] = unix_time_millis(datetime.datetime.now())
cursor.execute (cql_statement, rename_dict)
Run Code Online (Sandbox Code Playgroud)

您可以将日期时间转换为包含自纪元以来的毫秒数的长值,并且全部,使用时间戳的长值将更新转换为等效表单.

希望它能帮助别人


web*_*kie 5

对我而言,它直接适用

update test set last_sent = '2013-05-13 15:12:51' where id = 'someid'
Run Code Online (Sandbox Code Playgroud)

无需转换某些东西.所以在Python中你可以使用datetime值作为字符串:

cursor.execute("UPDATE test SET ts=:ts WHERE id=:id;",
    dict(ts=your_datetime.isoformat(), id=id))
Run Code Online (Sandbox Code Playgroud)