Marshalling time.Time to unix timestamp
NickName:gempir Ask DateTime:2018-09-23T15:40:13

Marshalling time.Time to unix timestamp

I have a struct like so

type log struct {
    [...]
    Timestamp timestamp `json:"timestamp"`
}

and I want to have the Timestamp as unix timestamp instead of whatever go does by default (2018-09-21T19:31:03.291Z)

I've tried creating a custom type for that like this:

type timestamp struct {
    time.Time
}

func (t timestamp) MarshalJSON() ([]byte, error) {
    return []byte(strconv.FormatInt(time.Time(t.Time).Unix(), 10)), nil
}

func (t *timestamp) UnmarshalJSON(data []byte) error {
    i, err := strconv.ParseInt(string(data[:]), 10, 64)
    if err != nil {
        return err
    }
    t = &timestamp{
        time.Unix(i, 0),
    }
    return nil
}

but I'm always getting the error can not unmarshal timestamp into *main.timestamp when trying to read from the database.

for iter.Scan(&message.Text, &message.Timestamp) {

    userlogResult.Messages = append(userlogResult.Messages, message)
}
if err := iter.Close(); err != nil {
    log.Error(err)
}

It can't unmarshall the Timestamp here. https://github.com/gocql/gocql/blob/799fb0373110eaa4e2e71dd32a9b5903f80dca8f/helpers.go#L30 the issue is that it doesn't use the Unmarshall functions.

Edit: I've answered my own question.

Copyright Notice:Content Author:「gempir」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/52464058/marshalling-time-time-to-unix-timestamp

Answers
Sarath Sadasivan Pillai 2018-09-23T09:09:51

here when assigning &timestamp{..} to t it is changing the pointer instead the value it is pointed to has to be chaged as follows\n\nfunc (t *timestamp) UnmarshalJSON(data []byte) error {\n i, err := strconv.ParseInt(string(data[:]), 10, 64)\n if err != nil {\n return err\n }\n *t = timestamp{\n time.Unix(i, 0),\n }\n return nil\n}\n\n\nPlease find code here\n\nEdit\n\nSince you are failing to unmarshall when reading from Database it is not because of json.unmarshalling you have to implement sql.Scanner\nif you are using sql \n\nPlease find the details here => sql.Scanner",


Oliver Jackman 2018-09-23T09:21:18

I think your code is ok - apart from the code in your unmarshal. You don't show the code where you are Marshalling/Unmarshalling which is where the actual error is.\n\nI have it working on the playground. Golang Playground\n\nInstead of this (which changes the pointer)\n\nt = &timestamp{\n time.Unix(i, 0),\n}\n\n\nChange the value\n\nt.Time = time.Unix(i,0)\n\n\nMain function to use your structs\n\nfmt.Println(\"First Log...\")\nl := log{Timestamp: timestamp{time.Now()}}\nfmt.Println(l)\n\nbuf, err := json.Marshal(l)\nif err != nil {\n panic(err)\n}\nfmt.Println(\"Marshalled to JSON...\")\nfmt.Printf(\"%s\\n\", buf)\n\nvar logCopy log\nif err := json.Unmarshal(buf, &logCopy); err != nil {\n panic(err)\n}\nfmt.Println(\"UnMarshalled from JSON...\")\nfmt.Println(logCopy)\n",


More about “Marshalling time.Time to unix timestamp” related questions

Marshalling time.Time to unix timestamp

I have a struct like so type log struct { [...] Timestamp timestamp `json:"timestamp"` } and I want to have the Timestamp as unix timestamp instead of whatever go does by default (2018-09-

Show Detail

Marshalling Time fields as Unix time

I want to encode my time.Time fields as numeric Unix time and I would prefer not to implement custom MarshalJSON functions for each and every struct, since I have lots and lots of structs. So, I t...

Show Detail

converting unix timestamp to local time

I'm attempting to convert time.time() to the local time. Reading python datetime to unix timestamp, I understand there's some limitations given that the timestamp is in UTC. However, in lieu of just

Show Detail

How to print the UTC UNIX Epoch/timestamp?

When I print the unix epoch, with something like time.time() it seems to print the timestamp in my local timezone. Especially from what converters like: https://www.epochconverter.com tell me. Does

Show Detail

How to print the UTC UNIX Epoch/timestamp?

When I print the unix epoch, with something like time.time() it seems to print the timestamp in my local timezone. Especially from what converters like: https://www.epochconverter.com tell me. Does

Show Detail

How to print the UTC UNIX Epoch/timestamp?

When I print the unix epoch, with something like time.time() it seems to print the timestamp in my local timezone. Especially from what converters like: https://www.epochconverter.com tell me. Does

Show Detail

Generate python UNIX timestamp

I am working with the kraken and binance APIs. The binance API returns a time like this: 1612722603026 inside of the API response. The kraken API does not return a time for the API response so I am

Show Detail

Sqlite datetime comparison with a unix timestamp

The Sqlite documentation states: SQLite has no DATETIME datatype. Instead, dates and times can be stored in any of these ways: As a TEXT string in the ISO-8601 format. Example: '2018-04-02 12:13:...

Show Detail

Timestamps in QuestDB Python time.time() Not working

ı am building a database in QuestDB. ı set up a table and one column is timestamp. docs about table = https://questdb.io/docs/guides/working-with-timestamps-timezones/ timestamp column is converting

Show Detail

How can I get the Unix timestamp in a file?

My goal is to write a script which will once I run it write the current Unix timestamp to a file. I tried several scripts which show the Unix timestamp directly such as this: import time print tim...

Show Detail