duanfei8897 2018-04-06 11:14
浏览 474
已采纳

如何从没有时区的Postgresql中获取时间戳值?

I have a table with timestamp TIMESTAMP, data TEXT columns. I have a failing test because I can't get a timestamp value out of postgresql without time zone annotation. Here's an abridged version of what I've done in my Go application:

type Datapoint struct {
    Timestamp  string
    Data       sql.NullString
}
var testData = Datapoint{Timestamp:'2018-12-31 00:00:00', Data:'test'}

db.Exec("CREATE TABLE mytable (id SERIAL, timestamp TIMESTAMP, data TEXT);")
db.Exec("INSERT INTO mytable(timestamp, data) VALUES ($1, $2);", testData.Timestamp, testData.Data)
datapoints, err = db.Exec("SELECT timestamp::TIMESTAMP WITHOUT TIME ZONE, data FROM mytable;")

This trouble is that this query (after about 20 lines of error checking and row.Scan; golang's a bit verbose like that...) gives me:

expected 2018-12-31 00:00:00, received 2018-12-31T00:00:00Z

I requested without timezone (and the query succeeds in psql), so why am I getting the extra T and Z in the string?

  • 写回答

2条回答 默认 最新

  • duanpang5583 2018-04-06 11:52
    关注

    Scan into a value of time.Time instead of string, then you can format the time as desired.

    package main
    
    import (
        "database/sql"
        "fmt"
        "log"
        "time"
    )
    
    type Datapoint struct {
        Timestamp time.Time
        Data      sql.NullString
    }
    
    func main() {
        var db *sql.DB
    
        var dp Datapoint    
        err := db.QueryRow("SELECT timestamp, data FROM mytable").Scan(
            &dp.Timestamp, &dp.Data,
        )
    
        switch {
        case err == sql.ErrNoRows:
            log.Fatal("No rows")
        case err != nil:
            log.Fatal(err)
        default:
            fmt.Println(dp.Timestamp.Format("2006-01-02 15:04:05"))
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器