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)
    }
}
datetime
{ "datetime": 1465793854 }
datetime
panic: parsing time "1465793854" as ""2006-01-02T15:04:05Z07:00"": cannot parse "1465793854" as """

Time.time
{ "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"

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

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

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



1> Aruna Herath..:
time.Time
time.Time
t.Format(time.RFC3339)

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

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

d := DataBlob{Datetime: t}
enc := json.NewEncoder(fileWriter)
enc.Encode(d)