Home > Back-end >  Calculate the 15 min time bin the current time falls into using go
Calculate the 15 min time bin the current time falls into using go

Time:02-13

So I am unaware on how to calculate the 15 min time bin for the current time. A day has 1440 minutes. So 96 - 15 min bins. So how can i calculate the time bin in golang?

func getCurrentMinutes(current time.Time) (int, error) {
   min, err := strconv.Atoi(current.Format("04"))
   if err != nil {
      return 0, err
   }
   return min, nil
}
func GetTimeBin(current time.Time, binDuration float64) float64 {
     min, _ := getCurrentMinutes(current)
     bin := float64(min) / binDuration
     return math.Ceil(bin)
}

The above implementation I have done is wrong as I am considering 15 min bins for an hour. I need to find the 15 min bin for the current time in the context of the day.

Thanks in advance!

CodePudding user response:

This is the working example I came up with.

func GetTimeBin(current time.Time, binDuration float64) float64 {
  hours := current.Hour()
  min := current.Minute()   hours*60
  bin := float64(min) / binDuration
  return math.Ceil(bin)
}

CodePudding user response:

how to calculate the 15 min time bin for the current time.


Here is a one-based bin index solution:

package main

import (
    "fmt"
    "time"
)

// timeBin returns the UTC daily one-based bin index
// for bins of size minutes.
func timeBin(t time.Time, size int) int {
    if size == 0 {
        return 1
    }
    if size < 0 {
        size = -size
    }

    h, m, _ := t.UTC().Clock()
    return (h*60 m)/size   1
}

func main() {
    t := time.Now()
    fmt.Println(timeBin(t, 15), t.UTC())
}

https://go.dev/play/p/fZhswWq9zv7

93 2009-11-10 23:00:00  0000 UTC

Here is a zero-based bin index solution:

package main

import (
    "fmt"
    "time"
)

// timeBin returns the UTC daily zero-based bin index
// for bins of size minutes.
func timeBin(t time.Time, size int) int {
    if size == 0 {
        return 0
    }
    if size < 0 {
        size = -size
    }

    h, m, _ := t.UTC().Clock()
    return (h*60   m) / size
}

func main() {
    t := time.Now()
    fmt.Println(timeBin(t, 15), t.UTC())
}

https://go.dev/play/p/K8ULH0_2wXO

92 2009-11-10 23:00:00  0000 UTC

  • Related