Go语言中时间片处理
工作中需要创建连续的时间片,找了许久,没找到Go语言快速生成时间片的函数包,算了,自己写一个吧
该函数类似于python中的pd.date_range()函数,功能相似,但是略有不同。
函数功能说明:
Start, End 为起止时间
根据feq的不同,当feq大于0时,可根据需要分的时间片个数分;
当feq小于0时,可以根据自己设定格式分,其中,-1:Second -2:Minute -3:Hour -4:Day -5:Month,各有所指,此时,slice输入为要分的具体数值,feq为单位
package main
import (
"fmt"
"time"
)
// TimeSlice ...
type TimeSlice struct {
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
}
// GenTimeSlice ...
// 参数说明:
// Start End time.Time 起止时间
// feq int 可输入的值(正数:时间片个数另可作为slice的单位:-1:Second -2:Minute -3:Hour -4:Day -5:Month)
// slice float32 浮点数: 时间片的大小,单位由feq决定
func GenTimeSlice(Start, End time.Time, feq int, slice float32) ([]TimeSlice, bool) {
if Start.After(End) {
return nil, false
}
result := []TimeSlice{TimeSlice{Start, End}}
if feq > 0 {
// 按个数生成时间片
result = genByNums(Start, End, feq)
return result, true
}
if slice <= 0 {
return result, true
}
Gap := End.Unix() - Start.Unix()
var Step int64
switch feq {
case -1: // Second
Step = int64(slice)
break
case -2: // Minute
Step = int64(slice * 60)
break
case -3: // Hour
Step = int64(slice * 60 * 60)
break
case -4: // Day
Step = int64(slice * 60 * 60 * 24)
break
case -5: // Week
Step = int64(slice * 60 * 60 * 24 * 7)
break
case -6: // Month
Step = int64(slice * 60 * 60 * 24 * 30)
break
default:
return result, true
}
if Gap < Step {
return result, true
}
result = genByStep(Start, End, Step)
return result, true
}
// genByMin ...
func genByStep(Start, End time.Time, Step int64) []TimeSlice {
timeDistance := End.Unix() - Start.Unix()
count := timeDistance / Step
result := make([]TimeSlice, 0)
for i := 0; i < int(count); i++ {
newGap := int64(i)*Step + Start.Unix()
start := time.Unix(newGap, 0)
newGap = int64(i+1)*Step + Start.Unix()
end := time.Unix(newGap, 0)
timeSliceTmp := TimeSlice{StartTime: start, EndTime: end}
result = append(result, timeSliceTmp)
}
return result
}
// genByNums ...
func genByNums(Start, End time.Time, feq int) []TimeSlice {
timeDistance := End.Unix() - Start.Unix()
timeStep := timeDistance / int64(feq)
result := make([]TimeSlice, 0)
for i := 0; i < feq; i++ {
newGap := int64(i)*timeStep + Start.Unix()
start := time.Unix(newGap, 0)
newGap = int64(i+1)*timeStep + Start.Unix()
end := time.Unix(newGap, 0)
timeSliceTmp := TimeSlice{StartTime: start, EndTime: end}
result = append(result, timeSliceTmp)
}
return result
}
func main() {
s1 := time.Unix(1568516266, 0)
s2 := time.Now().Local()
if kkk, ok := GenTimeSlice(s1, s2, -3, 2.5); ok {
fmt.Println("序号", "\t", "起始时间", "\t\t", "终止时间")
for i, val := range kkk {
fmt.Println(i+1, "\t", val.StartTime.Format("2006-01-02 15:04"), "\t", val.EndTime.Format("2006-01-02 15:04"))
}
}
}
输出:
序号 起始时间 终止时间 1 2019-09-15 10:57 2019-09-15 13:27 2 2019-09-15 13:27 2019-09-15 15:57 3 2019-09-15 15:57 2019-09-15 18:27 4 2019-09-15 18:27 2019-09-15 20:57 5 2019-09-15 20:57 2019-09-15 23:27 6 2019-09-15 23:27 2019-09-16 01:57 7 2019-09-16 01:57 2019-09-16 04:27 ...
附注:Go中Time包的使用

浙公网安备 33010602011771号