在Golang中完全解析时间戳

Jam*_*lor 7 postgresql datetime json go unmarshalling

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

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

type DataBlob struct {
  ....
  Datetime time.Time `json:"datetime, string"`
  ....
}
Run Code Online (Sandbox Code Playgroud)

并解析看起来像这样的代码:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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

{ "datetime": 1465793854 }
Run Code Online (Sandbox Code Playgroud)

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

panic: parsing time "1465793854" as ""2006-01-02T15:04:05Z07:00"": cannot parse "1465793854" as """
Run Code Online (Sandbox Code Playgroud)

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

{ "datetime": "2016-06-13 00:23:34 -0400 EDT" }
Run Code Online (Sandbox Code Playgroud)

当我去解析时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"
Run Code Online (Sandbox Code Playgroud)

如果我也将此时间戳(看起来相当标准)视为字符串并避免Marshaling问题,Postgres会在我尝试执行插入时抱怨:

panic: pq: invalid input syntax for type timestamp: "2016-06-13 00:23:34 -0400 EDT"
Run Code Online (Sandbox Code Playgroud)

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

如何解析此时间戳以执行数据库插入?为冗长的问题道歉并感谢您的帮助!

Aru*_*ath 7

JSON解组time.Time 期望日期字符串为RFC 3339格式.

因此,在生成JSON的golang程序中time.Time,使用Format以RFC 3339格式打印,而不是简单地打印该值.

t.Format(time.RFC3339)
Run Code Online (Sandbox Code Playgroud)

如果我序列化Time.time类型,我认为应该在该过程的另一侧理解它

如果您使用Marshaller接口进行序列化,它确实会以RFC 3339格式输出日期.因此,该过程的另一方将理解它.所以你也可以这样做.

d := DataBlob{Datetime: t}
enc := json.NewEncoder(fileWriter)
enc.Encode(d)
Run Code Online (Sandbox Code Playgroud)


Tec*_*ter 5

作为参考,如果您需要使用时间类型进行自定义解组,则需要使用 UnmarshalJSON 方法创建自己的类型。这是一个例子:

type Timestamp struct {
    time.Time
}

// UnmarshalJSON decodes an int64 timestamp into a time.Time object
func (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
}
Run Code Online (Sandbox Code Playgroud)

然后使用结构中的类型:

type DataBlob struct {
  ....
  Datetime Timestamp `json:"datetime"`
  ....
}
Run Code Online (Sandbox Code Playgroud)