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 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误