为了账号安全,请及时绑定邮箱和手机立即绑定

在 Golang 中完全解析时间戳

在 Golang 中完全解析时间戳

Go
守候你守候我 2022-01-17 18:05:21
我正在尝试制作一个简单的工具来解析文件中 JSON 格式的行并对INSERT数据库执行操作。我有一个看起来像这样的结构:type DataBlob struct {  ....  Datetime time.Time `json:"datetime, string"`  ....}并解析如下所示的代码:scanner := bufio.NewScanner(file)// Loop through all lines in the filefor 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类型,我认为它仍然应该在过程的另一端被理解。我该如何解析这个时间戳来执行数据库插入?为冗长的问题道歉,并感谢您的帮助!
查看完整描述

2 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

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)


查看完整回答
反对 回复 2022-01-17
?
catspeake

TA贡献1111条经验 获得超0个赞

作为参考,如果您需要使用时间类型进行自定义解组,则需要使用 UnmarshallJSON 方法创建自己的类型。带有时间戳的示例


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

}

然后在你的结构中使用类型:


type DataBlob struct {

  ....

  Datetime Timestamp `json:"datetime"`

  ....

}


查看完整回答
反对 回复 2022-01-17
  • 2 回答
  • 0 关注
  • 245 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号