Skip to content

Instantly share code, notes, and snippets.

@florentchauveau
Created August 30, 2018 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save florentchauveau/0ab3459d349b30bc78c6e9409e44e88a to your computer and use it in GitHub Desktop.
Save florentchauveau/0ab3459d349b30bc78c6e9409e44e88a to your computer and use it in GitHub Desktop.
// ConvertTS converts a UNIX timestamp string (with sub second precision) "epoch" into a time.Time
// (c) Florent CHAUVEAU <florent.chauveau@gmail.com>
func ConvertTS(ts string) time.Time {
value := strings.SplitN(ts, ".", 2)
var sec int64
var nsec int64
if len(value) == 0 {
return time.Time{}
}
if len(value) == 1 {
sec, _ = strconv.ParseInt(value[0], 10, 64)
} else if len(value) == 2 {
sec, _ = strconv.ParseInt(value[0], 10, 64)
nsec, _ = strconv.ParseInt(value[1], 10, 64)
// "1527589078.5418" -> 541800000 nsec
// "1527589067.8157027" -> 815702700 nsec
// "1527589073.0891006" -> 89100600 nsec
// " .000000001" (1 nsec)
// " .000000042" (42 nsec)
// " .000000423" (423 nsec)
x := 9 - len(value[1])
if x > 0 {
// "5418" becomes 541800000
// "0891006" becomes 89100600
// "000000001" stays 000000001
nsec = nsec * int64(math.Pow10(x))
}
}
return time.Unix(sec, nsec).UTC()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment