在 Golang 中完全解析时间戳

我正在尝试制作一个简单的工具来解析文件中 JSON 格式的行并对INSERT数据库执行操作。


我有一个看起来像这样的结构:


type DataBlob struct {

  ....

  Datetime time.Time `json:"datetime, string"`

  ....

}

并解析如下所示的代码:


scanner := bufio.NewScanner(file)

// Loop through all lines in the file

for scanner.Scan() {

    var t DataBlob


    // Decode the line, parse the JSON

    dec := json.NewDecoder(strings.NewReader(scanner.Text()))

    if err := dec.Decode(&t);

    err != nil {

        panic(err)

    }


    // Perform the database operation

    executionString: = "INSERT INTO observations (datetime) VALUES ($1)"

    _, err := db.Exec(executionString, t.Datetime)

    if err != nil {

        panic(err)

    }

}

我的 JSON 文件有几行,每行都包含一个datetime如下所示的值:


{ "datetime": 1465793854 }

当datetime格式化为 Unix 时间戳时,Marshaller 会抱怨:


panic: parsing time "1465793854" as ""2006-01-02T15:04:05Z07:00"": cannot parse "1465793854" as """

在生成 JSON 的脚本(也是用 Golang 编写的)中,我尝试简单地打印该Time.time类型的 String 表示,生成以下内容:


{ "datetime": "2016-06-13 00:23:34 -0400 EDT" }

当我去解析它时,Marshaller 抱怨它:


panic: parsing time ""2016-06-13 00:23:34 -0400 EDT"" as ""2006-01-02T15:04:05Z07:00"": cannot parse " 00:23:34 -0400 EDT"" as "T"

如果我还将这个时间戳(看起来很标准)视为一个字符串并避免编组问题,当我尝试执行插入时 Postgres 会抱怨:


panic: pq: invalid input syntax for type timestamp: "2016-06-13 00:23:34 -0400 EDT"

这在许多层面上令人沮丧,但主要是因为如果我序列化一个Time.time类型,我认为它仍然应该在过程的另一端被理解。


我该如何解析这个时间戳来执行数据库插入?为冗长的问题道歉,并感谢您的帮助!


守候你守候我
浏览 246回答 2
2回答

GCT1015

JSON 解组time.Time 期望日期字符串为 RFC 3339 格式。因此,在生成 JSON 的 golang 程序中,不要简单地打印time.Time值,而是使用Format以 RFC 3339 格式打印它。t.Format(time.RFC3339)如果我序列化 Time.time 类型,我认为它仍然应该在流程的另一端被理解如果您使用Marshaller 接口进行序列化,它确实会以 RFC 3339 格式输出日期。所以过程的另一方会理解它。所以你也可以这样做。d := DataBlob{Datetime: t}enc := json.NewEncoder(fileWriter)enc.Encode(d)

catspeake

作为参考,如果您需要使用时间类型进行自定义解组,则需要使用 UnmarshallJSON 方法创建自己的类型。带有时间戳的示例type Timestamp struct {    time.Time}// UnmarshalJSON decodes an int64 timestamp into a time.Time objectfunc (p *Timestamp) UnmarshalJSON(bytes []byte) error {    // 1. Decode the bytes into an int64    var raw int64    err := json.Unmarshal(bytes, &raw)    if err != nil {        fmt.Printf("error decoding timestamp: %s\n", err)        return err    }    // 2 - Parse the unix timestamp    *&p.Time = time.Unix(raw, 0)    return nil}然后在你的结构中使用类型:type DataBlob struct {  ....  Datetime Timestamp `json:"datetime"`  ....}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go