Truncate Timestamps Into Hour Buckets

time.Truncate rounds timestamps down to a fixed multiple, so raw event times collapse into stable hour buckets for counters and reports.

GoData Integrity

Code

gosnippet
36 lines
package main

import (
	"fmt"
	"slices"
	"time"
)

func main() {
	requests := []time.Time{
		time.Date(2026, 11, 14, 9, 12, 0, 0, time.UTC),
		time.Date(2026, 11, 14, 9, 47, 0, 0, time.UTC),
		time.Date(2026, 11, 14, 10, 5, 0, 0, time.UTC),
	}

	// Truncate 向下取整到整倍数时长:把原始时间戳折进整点桶
	buckets := map[time.Time]int{}
	for _, ts := range requests {
		buckets[ts.Truncate(time.Hour)]++
	}

	// map 遍历无序:排序键后输出才是确定的
	keys := make([]time.Time, 0, len(buckets))
	for k := range buckets {
		keys = append(keys, k)
	}
	slices.SortFunc(keys, time.Time.Compare)
	for _, k := range keys {
		fmt.Printf("%s: %d requests\n", k.Format("15:04"), buckets[k])
	}

	// Truncate 按 UTC 绝对时间取整:本地时区的自然日要用
	// time.Date(y, m, d, 0, 0, 0, 0, loc) 构造,不能直接 Truncate(24h)
	utcDay := requests[0].Truncate(24 * time.Hour)
	fmt.Println("utc day:", utcDay.Format("2006-01-02"))
}

Inside the snippet

Count the function main as the entire surface area of Truncate Timestamps Into Hour Buckets.

Iteration happens inside for _, ts := range requests — everything outside it runs once.

Putting it to use

Look for the utc day: prefixes when the file runs; they tie each line to its step.

Core lines

for _, ts := range requests {
buckets[ts.Truncate(time.Hour)]++
}
for k := range buckets {
keys = append(keys, k)
}
for _, k := range keys {
fmt.Printf("%s: %d requests\n", k.Format("15:04"), buckets[k])
}

Interactive Tools for This Topic

FAQ

What does Truncate Timestamps Into Hour Buckets print when run?
Running the file directly is enough — expect labeled output lines such as `utc day:`.