将时间戳写入数据库 - gocql vs cqlsh

问题描述

在 cassandra 数据库中写入时间戳的所需格式:

  2021-01-17 21:51:46.195

使用 cqlsh 语法进行插入查询

  1. 能够使用 toTimeStamp(toDate(Now()))

    编写上述格式
  2. 使用 cqlsh,我无法使用 toUnixTimestamp(Now()) 编写上述格式。 toUnixTimestamp(Now()) 写入格式 2021-01-17 21:51:46.195000+0000


    layout := "2006-01-02T15:04:05.000Z"

    timestamp := "2021-01-17T21:51:46.195Z"
    createdDate,err := time.Parse(layout,timestamp)
    insertQueryString = "INSERT INTO mytable(created_date) " + "VALUES (?)"

gocql.Session.Query(insertQueryString,createdDate).Exec() 代码也将 createdDate 写入数据库,类似于 cqlsh 的 toUnixTimestamp(Now()) 的格式,即 2021-01-17 21:51:46.195000+0000 如下所示:

enter image description here


JimB 已经解释过:“再说一次,time.Time 没有格式。如果需要,您可以将其格式化为字符串,这在许多其他答案中都有解释。”

但是,

如何让gocql.Session.Query(insertQueryString,createdDate).Exec()createdDate写成2021-01-17 21:51:46.195?因为 cqlsh 使用 toTimeStamp(toDate(Now()))

能够编写这种所需的格式

解决方法

Cassandra 不将时间戳记为字符串,它作为 long 数字存储在数据库中,毫秒精度为 8 个字节(参见 protocol specification)。将数字转换为字符串是客户端程序的责任,cqlsh 是 Cassandra 附带的基于 python 的客户端。并且 cqlsh 具有控制如何呈现时间戳的配置选项 - 这是 cqlshrc configuration filedatetimeformat 选项,您可以根据需要自定义打印日期。