首页 > 解决方案 > 从 django 获取可以为空的日期时间并将其转换为 golang

问题描述

这是我从 jsonified models.DateTimeField 发送(以原始文本)模式的日期:

2019-05-07 16:49:47.351628+00:00

我如何在 golang 中收到它:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"

    "github.com/lib/pq"
)
type DataLink struct {
    Created     pq.NullTime `json:"created"`
}

type SendData struct {
    Name string `json:"Name"`
}

func main() {

    var reception = DataLink{}
    var sendData = SendData{}
    sendData.Name = "Melon"
    url := "http://127.0.0.1:8309/getLinks/"
    fmt.Println("URL:>", url)

    js, err := json.Marshal(sendData)

    req, err := http.NewRequest("POST", url, bytes.NewBuffer(js))
    req.Header.Set("X-Custom-Header", "myvalue")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    //fmt.Println("response Status:", resp.Status)
    //fmt.Println("response Headers:", resp.Header)
    body, _ := ioutil.ReadAll(resp.Body)
    //fmt.Println("response Body:", string(body))
    err = json.Unmarshal(body, &reception)
    fmt.Println(reception.Created)
}

但是当我打印我的对象时,我有一个:

{0001-01-01 00:00:00 +0000 UTC false}

如何从 django 时间字段或使用字符串操作我的日期时间以使其与 go 和 pq.NullTime 兼容?

其他一切都有效(bool、int、float、string)但不是日期...

标签: djangogo

解决方案


您需要自定义时间类型才能unmarshal自定义时间格式:

type Datetime struct {
    pq.NullTime
}

func (t *Datetime) UnmarshalJSON(input []byte) error {
    strInput := strings.Trim(string(input), `"`)
    newTime, err := time.Parse(time.RFC3339, strInput)
    if err != nil {
        return err
    }

    t.pqNullTime = newTime
    return nil
}

默认情况下,json unmarshal 需要RFC3339格式中的日期。


推荐阅读