dqcd84732 2017-11-02 03:40
浏览 224
已采纳

从Go中的秒表解析hh:mm:ss时间?

I have a series of stopwatch-like timestamps in a logfile formatted as hh:mm:ss, e.g. "00:03:30". How would I go about parsing such timestamps in Golang such that I could find the difference between two time intervals?

For example, substituting 00:03:30 and 00:03:00 should return 00:00:30 or 30.

  • 写回答

4条回答 默认 最新

  • duandange7480 2017-11-02 03:58
    关注

    You may subtract one time from another.

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
    
        t1, err := time.Parse("15:04:05", "03:00:30")
        t2, err := time.Parse("15:04:05", "03:00:00")
    
        fmt.Println(err, t1.Sub(t2), t1.Sub(t2).Seconds())
    }
    

    Working example - https://play.golang.org/p/VegXLBvfnM

    UPDATE: How to cope with durations over 24:00:00? This way they can be parsed manually:

    func Parse(st string) (int, error) {
        var h, m, s int
        n, err := fmt.Sscanf(st, "%d:%d:%d", &h, &m, &s)
        fmt.Print(n, err)
        if err != nil || n != 3 {
            return 0, err  
        }
        return h*3600 + m*60 + s, nil
    }
    

    https://play.golang.org/p/HHSRHzaGqT

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料