划分时间。 Golang 中的 Duration

Pat*_*nes 4 go

At present, the time package in Go has no 'divide' function or anything similar. You can divide a time.Duration by some other value, but it requires a fair bit of casting. Is there any easy/obvious way to divide a time.Duration by something in Go that I'm not seeing? (I know you can divide by a numeric constant, but I need to do it on a dynamic basis.) I'm planning on submitting a issue/feature request to add a basic 'divide' function to the time package, but I wanted to ask here first in case I'm missing some easy way to do this kind of division.

pet*_*rSO 7

打包时间

import "time" 
Run Code Online (Sandbox Code Playgroud)

为了避免夏令时时区转换之间的混淆,没有对 Day 或更大单位的定义。

要计算 Duration 中的单位数,请除以:

second := time.Second
fmt.Print(int64(second/time.Millisecond)) // prints 1000
Run Code Online (Sandbox Code Playgroud)

要将整数单位转换为持续时间,请乘以:

seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s

const (
        Nanosecond  Duration = 1
        Microsecond          = 1000 * Nanosecond
        Millisecond          = 1000 * Microsecond
        Second               = 1000 * Millisecond
        Minute               = 60 * Second
        Hour                 = 60 * Minute
)
Run Code Online (Sandbox Code Playgroud)

类型 持续时间

Duration 将两个瞬间之间经过的时间表示为 int64 纳秒计数。该表示将最大可表示持续时间限制为大约 290 年。

type Duration int64
Run Code Online (Sandbox Code Playgroud)

time.DurationGotime包文档中描述了 的除法和乘法。

  • `time` 包中给出的示例指示如何计算 Duration 中的单位数 - 例如,不会获得原始持续时间的 1/13 的持续时间。我知道你可以通过将 `time.Duration` 和除数转换为 `int64`,进行除法,然后调用 `time.Duration(result)` 来实现。我只是有点惊讶 `time` 没有“划分”方法或类似的方法。 (6认同)