gpt4 book ai didi

python - 获取时间窗口的楼层

转载 作者:行者123 更新时间:2023-12-01 20:18:42 25 4
gpt4 key购买 nike

我正在尝试将一些 Python 代码移植到 Go 中。我希望能够在一段时间内通过,然后根据当前时间获得发言权。例如,如果时间是 12:35:53 并且我在 5 秒内传递,则地板将是 12:35:50,我还需要能够传递步长值,所以如果我传递 -1 它将退回到前5个二楼,比如时间是12:35:53会回滚到12:35:45。

Python代码如下

window_length_as_seconds = window_length.total_seconds()
t = time()
remainder = t % window_length_as_seconds
window_start = t - remainder + step * window_length_as_seconds
return datetime.datetime.utcfromtimestamp(window_start)

这是我的代码示例链接

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

func GetWindow(windowLength time.Duration, step int64) time.Time {
now := Now().Unix()
remainder := now % int64(windowLength.Seconds())
windowStart := time.Unix(now-(remainder+step*int64(windowLength.Seconds())), 0)
return windowStart.UTC()
}

如果我在没有任何步骤的情况下在几秒钟内通过,但它会以相反的方式进行,并且当我在几分之一秒内通过时,它工作正常如果我将持续时间设置为“100ms”,我会收到以下错误:

panic: runtime error: integer divide by zero

与 Python 相比,我是否在 Go 中错误地处理了时间?

最佳答案

如果要向下舍入时间,请使用 time.Truncate :

t := time.Now()
fmt.Println(t.Truncate(5*time.Second))

根据您的需要应用它:

// returns in UTC timezone - regardless of input timezone
func getWindow(t time.Time, windowLength time.Duration, step int64) time.Time {
return t.UTC().Truncate(windowLength).Add(
time.Duration(step) * windowLength,
)
}

// time.Now() may be in any timezone - but UTC will be returned (see above)
func GetWindow(windowLength time.Duration, step int64) time.Time {
return getWindow(time.Now(), windowLength, step)
}

带有替代时区等的演示:https://play.golang.org/p/gqsT4LvWdDi

添加到您的测试代码:https://play.golang.org/p/UDPlsR6IGPw

关于python - 获取时间窗口的楼层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63888422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com