英文:
Time since golang nanosecond timestamp
问题
Q1. 如何从纳秒时间戳创建一个 Golang 的 time 结构体?
Q2. 然后如何计算自此时间戳以来的小时数?
英文:
Q1. How do I create a golang time struct from a nanosecond timestamp?
Q2. How do I then compute the number of hours since this timestamp?
答案1
得分: 21
在Go语言中,"time"对象由time.Time
结构类型的值表示。
你可以使用time.Unix(sec int64, nsec int64)
函数从纳秒时间戳创建一个Time
对象,其中可以传递超出范围[0, 999999999]
的nsec
值。
你可以使用time.Since(t Time)
函数,它返回自指定时间以来经过的时间,以time.Duration
的形式表示(基本上是以纳秒为单位的时间差)。
t := time.Unix(0, yourTimestamp)
elapsed := time.Since(t)
要获取经过的小时数,只需使用Duration.Hours()
方法,它以浮点数形式返回持续时间的小时数:
fmt.Printf("经过的时间:%.2f 小时", elapsed.Hours())
在Go Playground上试一试。
注意:
Duration
可以智能地以类似"72h3m0.5s"
的格式进行格式化,这是通过其String()
方法实现的:
fmt.Printf("经过的时间:%s", elapsed)
英文:
In Go a "time" object is represented by a value of the struct type time.Time
.
You can create a Time
from a nanosecond timestamp using the time.Unix(sec int64, nsec int64)
function where it is valid to pass nsec
outside the range [0, 999999999]
.
And you can use the time.Since(t Time)
function which returns the elapsed time since the specified time as a time.Duration
(which is basically the time difference in nanoseconds).
t := time.Unix(0, yourTimestamp)
elapsed := time.Since(t)
To get the elapsed time in hours, simply use the Duration.Hours()
method which returns the duration in hours as a floating point number:
fmt.Printf("Elapsed time: %.2f hours", elapsed.Hours())
Try it on the Go Playground.
Note:
Duration
can format itself intelligently in a format like "72h3m0.5s"
, implemented in its String()
method:
fmt.Printf("Elapsed time: %s", elapsed)
答案2
得分: 5
你将纳秒传递给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))
}
英文:
You pass the nanoseconds to time.Unix(0, ts)
, example:
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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论