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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Duration ConverterConvert between human durations like 1w2d3h45m and total seconds, hours, and minutes with negative support.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.ISO 8601 Duration ParserParse ISO 8601 durations like PT1H30M into year, month, week, day, and time components with exact or approximate total seconds.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.