本文整理汇总了Golang中Time.Time.Truncate方法的典型用法代码示例。如果您正苦于以下问题:Golang Time.Truncate方法的具体用法?Golang Time.Truncate怎么用?Golang Time.Truncate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Time.Time
的用法示例。
在下文中一共展示了Time.Truncate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: CreateShardGroup
// CreateShardGroup creates a shard group on a database and policy for a given timestamp.
func (data *Data) CreateShardGroup(database, policy string, timestamp time.Time) error {
// Find retention policy.
rpi, err := data.RetentionPolicy(database, policy)
if err != nil {
return err
} else if rpi == nil {
return influxdb.ErrRetentionPolicyNotFound(policy)
}
// Verify that shard group doesn't already exist for this timestamp.
if rpi.ShardGroupByTimestamp(timestamp) != nil {
return nil
}
// Create the shard group.
data.MaxShardGroupID++
sgi := ShardGroupInfo{}
sgi.ID = data.MaxShardGroupID
sgi.StartTime = timestamp.Truncate(rpi.ShardGroupDuration).UTC()
sgi.EndTime = sgi.StartTime.Add(rpi.ShardGroupDuration).UTC()
data.MaxShardID++
sgi.Shards = []ShardInfo{
{ID: data.MaxShardID},
}
// Retention policy has a new shard group, so update the policy. Shard
// Groups must be stored in sorted order, as other parts of the system
// assume this to be the case.
rpi.ShardGroups = append(rpi.ShardGroups, sgi)
sort.Sort(ShardGroupInfos(rpi.ShardGroups))
return nil
}
示例2: PurgeOlderThan
func (l *queue) PurgeOlderThan(when time.Time) error {
l.mu.Lock()
defer l.mu.Unlock()
if len(l.segments) == 0 {
return nil
}
cutoff := when.Truncate(time.Second)
for {
mod, err := l.head.lastModified()
if err != nil {
return err
}
if mod.After(cutoff) || mod.Equal(cutoff) {
return nil
}
// If this is the last segment, first append a new one allowing
// trimming to proceed.
if len(l.segments) == 1 {
_, err := l.addSegment()
if err != nil {
return err
}
}
if err := l.trimHead(); err != nil {
return err
}
}
}
示例3: processTimeRange
// processTimeRange calls gs.GetLatestGSDirs to get a list of
func (xformer *pdfXformer) processTimeRange(start time.Time, end time.Time) {
glog.Infof("Processing time range: (%s, %s)", start.Truncate(time.Second), end.Truncate(time.Second))
for _, dir := range gs.GetLatestGSDirs(start.Unix(), end.Unix(), *storageJsonDirectory) {
glog.Infof("> Reading gs://%s/%s\n", *storageBucket, dir)
requestedObjects := xformer.client.storageService.Objects.List(*storageBucket).Prefix(dir).Fields(
"nextPageToken", "items/updated", "items/md5Hash", "items/mediaLink", "items/name", "items/metadata")
for requestedObjects != nil {
responseObjects, err := requestedObjects.Do()
if err != nil {
glog.Errorf("request %#v failed: %s", requestedObjects, err)
} else {
for _, jsonObject := range responseObjects.Items {
xformer.counter++
glog.Infof("> > Processing object: gs://%s/%s {%d}", *storageBucket, jsonObject.Name, xformer.counter)
xformer.processJsonFile(jsonObject)
}
}
if len(responseObjects.NextPageToken) > 0 {
requestedObjects.PageToken(responseObjects.NextPageToken)
} else {
requestedObjects = nil
}
}
}
glog.Infof("finished time range.")
}
示例4: Begins
// Begins returns the timestamp of the beginning of this RRA assuming
// that that the argument "now" is within it. This will be a time
// approximately but not exactly the RRA length ago, because it is
// aligned on the RRA step boundary.
func (rra *RoundRobinArchive) Begins(now time.Time) time.Time {
rraStart := now.Add(rra.step * time.Duration(rra.size) * -1).Truncate(rra.step)
if now.Equal(now.Truncate(rra.step)) {
rraStart = rraStart.Add(rra.step)
}
return rraStart
}
示例5: ServiceEvents
// ServiceEvents returns an array of events for the specified service id. If start- and/or end is
// not nil the list if filtered to include only the events between start- and end time, inclusive.
//
// Note that only the date part of the start- and end times considered and parts with finer
// granularity are ignored.
func ServiceEvents(serviceId string, start *time.Time, end *time.Time) ([]ApiServiceEvent, error) {
v := struct {
ClientError
Events []ApiServiceEvent `json:"events"`
}{}
u, err := url.Parse(fmt.Sprintf("/v1/services/%s/events", serviceId))
if err != nil {
return nil, err
}
q := u.Query()
if start != nil {
q.Set("start", start.Truncate(24*time.Hour).Format(time.RFC1123))
}
if end != nil {
q.Set("end", end.Truncate(24*time.Hour).Format(time.RFC1123))
}
u.RawQuery = q.Encode()
if err = getStatus(u.String(), &v); err != nil {
return nil, err
}
if v.IsError {
return nil, &v.ClientError
}
return v.Events, nil
}
示例6: CannedSignedURL
// Creates a signed url using RSAwithSHA1 as specified by
// http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-creating-signed-url-canned-policy.html#private-content-canned-policy-creating-signature
func (cf *CloudFront) CannedSignedURL(path, queryString string, expires time.Time) (string, error) {
resource := cf.BaseURL + path
if queryString != "" {
resource = path + "?" + queryString
}
policy, err := buildPolicy(resource, expires)
if err != nil {
return "", err
}
signature, err := cf.generateSignature(policy)
if err != nil {
return "", err
}
// TOOD: Do this once
uri, err := url.Parse(cf.BaseURL)
if err != nil {
return "", err
}
uri.RawQuery = queryString
if queryString != "" {
uri.RawQuery += "&"
}
expireTime := expires.Truncate(time.Millisecond).Unix()
uri.Path = path
uri.RawQuery += fmt.Sprintf("Expires=%d&Signature=%s&Key-Pair-Id=%s", expireTime, signature, cf.keyPairId)
return uri.String(), nil
}
示例7: calcDailySummary
func calcDailySummary(now time.Time, config StartupConfig, runningConfig RunningConfig) {
log.Infof("lastSummaryTime is %v", runningConfig.LastSummaryTime)
if runningConfig.LastSummaryTime.Day() != now.Day() {
startTime := now.Truncate(24 * time.Hour).Add(-24 * time.Hour)
endTime := startTime.Add(24 * time.Hour)
log.Info("Summarizing from ", startTime, " (", startTime.Unix(), ") to ", endTime, " (", endTime.Unix(), ")")
// influx connection
influxClient, err := influxConnect(config, runningConfig)
if err != nil {
log.Error("Could not connect to InfluxDb to get daily summary stats!!")
errHndlr(err, ERROR)
return
}
bp, _ := influx.NewBatchPoints(influx.BatchPointsConfig{
Database: "daily_stats",
Precision: "s",
RetentionPolicy: config.DailySummaryRetentionPolicy,
})
calcDailyMaxGbps(influxClient, bp, startTime, endTime, config)
calcDailyBytesServed(influxClient, bp, startTime, endTime, config)
log.Info("Collected daily stats @ ", now)
}
}
示例8: TestParse
func TestParse(t *testing.T) {
var (
s string
p, x time.Time
err error
)
// Local time
now := time.Now()
times := map[string]time.Time{
"5m": now.Add(time.Duration(time.Minute * 5)),
"-0h": now.Add(-time.Duration(time.Hour * 0)),
"-48h5m": now.Add(-time.Duration(time.Hour*48 + time.Minute*5)),
// UTC
"2013-04-10": time.Date(2013, 4, 10, 0, 0, 0, 0, time.UTC),
"April 4, 2013": time.Date(2013, 4, 4, 0, 0, 0, 0, time.UTC),
"Apr 04, 2013": time.Date(2013, 4, 4, 0, 0, 0, 0, time.UTC),
"47065363200000000": time.Date(1492, 6, 11, 0, 0, 0, 0, time.UTC),
"02-01-2006": time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC),
"02-01-2006 2:04 PM": time.Date(2006, 1, 2, 14, 4, 0, 0, time.UTC),
"02-01-2006 2:04 PM -0700": time.Date(2006, 1, 2, 21, 4, 0, 0, time.UTC),
"02-01-2006 2:04 PM -07:00": time.Date(2006, 1, 2, 21, 4, 0, 0, time.UTC),
"2 January 2006": time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC),
"2 January 2006 3:04 PM": time.Date(2006, 1, 2, 15, 4, 0, 0, time.UTC),
"2 January 2006 3:04 PM -0700": time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
"2 January 2006 3:04 PM -07:00": time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
"2006-01-02": time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC),
"2006-01-02 3:04 PM": time.Date(2006, 1, 2, 15, 4, 0, 0, time.UTC),
"2006-01-02 3:04 PM -0700": time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
"2006-01-02 3:04 PM -07:00": time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
"January 2, 2006": time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC),
"January 2, 2006 3:04 PM": time.Date(2006, 1, 2, 15, 4, 0, 0, time.UTC),
"January 2, 2006 3:04 PM -0700": time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
"January 2, 2006 3:04 PM -07:00": time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
"Jan 2, 2006": time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC),
"Jan 2, 2006, 3:04 PM": time.Date(2006, 1, 2, 15, 4, 0, 0, time.UTC),
"Jan 2, 2006 3:04 PM -0700": time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
"Jan 2, 2006 3:04 PM -07:00": time.Date(2006, 1, 2, 22, 4, 0, 0, time.UTC),
}
// Duration to truncate for comparison.
td := time.Second
for s, x = range times {
p, err = Parse(s)
if err != nil {
t.Errorf("time: failed to parse %s as time", s)
} else {
x = x.Truncate(td)
p = p.Truncate(td)
if !p.Equal(x) {
t.Errorf("time: expected %s, got %s", x, p)
}
}
}
}
示例9: NewDateTime
// creates a new caldav datetime representation, must be in UTC
func NewDateTime(name string, t time.Time) (*DateTime, error) {
if t.Location() != time.UTC {
return nil, errors.New("CalDAV datetime must be in UTC")
} else {
return &DateTime{name: name, t: t.Truncate(time.Second)}, nil
}
}
示例10: surroundingStep
// surroundingStep returns begin and end of a PDP which either
// includes or ends on a given time mark.
func surroundingStep(mark time.Time, step time.Duration) (time.Time, time.Time) {
begin := mark.Truncate(step)
if mark.Equal(begin) { // We are exactly at the end, need to move one step back.
begin = begin.Add(step * -1)
}
return begin, begin.Add(step)
}
示例11: NextSchedule
func NextSchedule(now time.Time, offset time.Duration, d time.Duration) time.Time {
t := now.Truncate(d).Add(offset)
if t.After(now) {
return t
} else {
return t.Add(d)
}
}
示例12: throttle
func (t *threadThrottler) throttle(now time.Time) time.Duration {
// Initialize or advance the current second interval when necessary.
nowSecond := now.Truncate(time.Second)
if !t.initialized {
t.resetSecond(nowSecond)
t.initialized = true
}
if !t.currentSecond.Equal(nowSecond) {
t.resetSecond(nowSecond)
}
maxRate := t.maxRateSecond
if maxRate == ZeroRateNoProgess {
// Throughput is effectively paused. Do not let anything through until
// the max rate changes.
return t.currentSecond.Add(1 * time.Second).Sub(now)
}
// Check if we have already received too many requests within this second.
if t.currentRate >= maxRate {
return t.currentSecond.Add(1 * time.Second).Sub(now)
}
// Next request isn't expected earlier than nextRequestInterval.
// With this check we ensure there's one request per request interval at most.
if now.Before(t.nextRequestInterval) {
return t.nextRequestInterval.Sub(now)
}
// Check if we have to pace the user.
// NOTE: Pacing won't work if maxRate > 1e9 (since 1e9ns = 1s) and therefore
// the returned backoff will always be zero.
// Minimum time between two requests.
requestIntervalNs := (1 * time.Second).Nanoseconds() / maxRate
// End of the previous request is the earliest allowed time of this request.
earliestArrivalOffsetNs := t.currentRate * requestIntervalNs
earliestArrival := t.currentSecond.Add(time.Duration(earliestArrivalOffsetNs) * time.Nanosecond)
// TODO(mberlin): Most likely we overshoot here since we don't take into
// account our and the user's processing time. Due to too long backoffs, they
// might not be able to fully use their capacity/maximum rate.
backoff := earliestArrival.Sub(now)
if backoff > 0 {
return backoff
}
// Calculate the earlist time the next request can pass.
requestInterval := time.Duration(requestIntervalNs) * time.Nanosecond
currentRequestInterval := now.Truncate(requestInterval)
t.nextRequestInterval = currentRequestInterval.Add(requestInterval)
// QPS rates >= 10k are prone to skipping their next request interval.
// We have to be more relaxed in this case.
if requestInterval <= 100*time.Microsecond {
t.nextRequestInterval = t.nextRequestInterval.Add(-requestInterval)
}
t.currentRate++
return NotThrottled
}
示例13: testBucket
func testBucket(name, source, user, pass string, t time.Time, res time.Duration, vals []float64) *bucket.Bucket {
id := new(bucket.Id)
id.Name = name
id.Source = source
id.User = user
id.Pass = pass
id.Time = t.Truncate(res)
id.Resolution = res
return &bucket.Bucket{Id: id, Vals: vals}
}
示例14: On
// On filters journal entries by creation date
func (journal Journal) On(on time.Time) *Journal {
var results []entry.Entry
for _, entry := range journal.Query() {
if entry.CreatedAt.Truncate(24 * time.Hour).Equal(on.Truncate(24 * time.Hour)) {
results = append(results, entry)
}
}
return &Journal{results}
}
示例15: IfModifiedSince
// IfModifiedSince returns true if lastModified exceeds 'If-Modified-Since'
// value from the request header.
//
// The function returns true also 'If-Modified-Since' request header is missing.
func (ctx *RequestCtx) IfModifiedSince(lastModified time.Time) bool {
ifModStr := ctx.Request.Header.peek(strIfModifiedSince)
if len(ifModStr) == 0 {
return true
}
ifMod, err := ParseHTTPDate(ifModStr)
if err != nil {
return true
}
lastModified = lastModified.Truncate(time.Second)
return ifMod.Before(lastModified)
}