douti0687 2015-02-27 00:59
浏览 330
已采纳

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

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?

  • 写回答

2条回答 默认 最新

  • douliao8760 2015-02-27 08:39
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 无源定位系统的时差估计误差标准差
  • ¥15 请问这个代码哪里有问题啊
  • ¥20 python--version在命令端输入结果Python is not defined怎么办?还有pip不是exe格式是不是没安装成功?
  • ¥15 通过GaussianView进行结构微调消除虚频
  • ¥15 调用transformers库
  • ¥15 由于导出的数据名字中带有/,导致Matlab打不开,怎么办?
  • ¥15 新硬盘安装的程序总是崩溃,提示遇到错误
  • ¥15 openpcdet自制数据集评估bev精度和3d精度相同
  • ¥15 excel 上下按钮 显示行
  • ¥20 云卓h12pro 数传问题