自 golang 纳秒时间戳以来的时间

Time since golang nanosecond timestamp

Q1. 如何从纳秒时间戳创建 golang time 结构?

问题 2. 我如何计算自该时间戳以来的小时数?

您将纳秒传递给 time.Unix(0, ts),示例:

func main() {
    now := time.Now()
    ts := int64(1257856852039812612)
    timeFromTS := time.Unix(0, ts)
    diff := now.Sub(timeFromTS)
    fmt.Printf("now: %v\ntime from ts: %v\ndiff: %v\ndiff int:", now, timeFromTS, diff, int64(diff))
}

playground

在 Go 中,"time" 对象由结构类型 time.Time.

的值表示

您可以使用 time.Unix(sec int64, nsec int64) 函数从纳秒时间戳创建 Time,其中在 [0, 999999999].[=30= 范围之外传递 nsec 是有效的]

并且你可以使用time.Since(t Time) function which returns the elapsed time since the specified time as a time.Duration(这基本上是以纳秒为单位的时间差)。

t := time.Unix(0, yourTimestamp)
elapsed := time.Since(t)

要获得以小时为单位的经过时间,只需使用 Duration.Hours() 方法,其中 returns 以小时为单位的持续时间作为浮点数:

fmt.Printf("Elapsed time: %.2f hours", elapsed.Hours())

Go Playground 上试试。

注:

Duration 可以智能地以类似 "72h3m0.5s" 的格式自行格式化,在其 String() 方法中实现:

fmt.Printf("Elapsed time: %s", elapsed)