Home > database >  Parsing ticker with datetime and dropping time elapsed
Parsing ticker with datetime and dropping time elapsed

Time:01-05

I would like to get a datetime from a ticker.C formatted string (over the network) and parse it into a Time object. ticker.C would look like 2023-01-03 17:24:13.986722973 0100 CET m= 1.002332450. It would probably have to drop the m= 1.002332450 elapsed time as I don't see a way of keeping that in a Time object.

Also, is there a way to get a format string out of a Time object? Something like mytime.GetFormat()

CodePudding user response:

The Stringer format of Time is documented here, https://pkg.go.dev/[email protected]#Time.String:

String returns the time formatted using the format string

"2006-01-02 15:04:05.999999999 -0700 MST"

If the time has a monotonic clock reading, the returned string includes a final field "m=±<value>", where value is the monotonic clock reading formatted as a decimal number of seconds.

The returned string is meant for debugging; for a stable serialized representation, use t.MarshalText, t.MarshalBinary, or t.Format with an explicit format string.

Which suggests you should not try to consume that value and instead depend on a properly marshalled (or formatted) string.

Not mentioned/suggested, time.MarshalJSON is an option:

MarshalJSON implements the json.Marshaler interface. The time is a quoted string in RFC 3339 format, with sub-second precision added if present.

The sender and receiver don't have to do any special work to encode the time.Time value in JSON and then decode it again:

type wireTick struct {
    Tick time.Time `json:"tick"`
}

Here's a small example of encoding and decoding the ticker on the wire with that struct, https://go.dev/play/p/Fx73q8-kVFa, which produces output like:

Sent JSON-encoded tick on wire: {"tick":"2009-11-10T23:00:01Z"}
Received tick from wire:        {2009-11-10 23:00:01  0000 UTC}
Sent JSON-encoded tick on wire: {"tick":"2009-11-10T23:00:02Z"}
Received tick from wire:        {2009-11-10 23:00:02  0000 UTC}
...

Can you modify the value being sent on the wire, or ask someone else to modify it so that it's proper?

If not, this should work:

const stringerLayout = "2006-01-02 15:04:05.999999999 -0700 MST"

timeStr := "2009-11-10 23:00:10  0000 UTC m= 10.000000001"
tickStr := timeStr[:strings.Index(timeStr, "m=")-1]
tick, _ := time.Parse(stringerLayout, tickStr)

fmt.Printf("Received from wire: \t %q\n", timeStr)
fmt.Printf("Chopped off monotonic: \t %q\n", tickStr)
fmt.Printf("Tick is: \t\t %v\n", tick)
Received from wire:      "2009-11-10 23:00:10  0000 UTC m= 10.000000001"
Chopped off monotonic:   "2009-11-10 23:00:10  0000 UTC"
Tick is:                 2009-11-10 23:00:10  0000 UTC
  •  Tags:  
  • go
  • Related