How to Round a Time Down to the Nearest 15 Minutes in Ruby

How to round a time down to the nearest 15 minutes in Ruby?

You said "round down", so I'm not sure if you're actually looking for the round or the floor, but here's the code to do both. I think something like this reads really well if you add round_off and floor methods to the Time class. The added benefit is that you can more easily round by any time partition.

require 'active_support/core_ext/numeric' # from gem 'activesupport'

class Time
# Time#round already exists with different meaning in Ruby 1.9
def round_off(seconds = 60)
Time.at((self.to_f / seconds).round * seconds).utc
end

def floor(seconds = 60)
Time.at((self.to_f / seconds).floor * seconds).utc
end
end

t = Time.now # => Thu Jan 15 21:26:36 -0500 2009
t.round_off(15.minutes) # => Thu Jan 15 21:30:00 -0500 2009
t.floor(15.minutes) # => Thu Jan 15 21:15:00 -0500 2009

Note: ActiveSupport was only necessary for the pretty 15.minutes argument. If you don't want that dependency, use 15 * 60 instead.

rounding a Rails DateTime to the nearest 15 minute interval

The following should do the trick:

##
# rounds a Time or DateTime to the neares 15 minutes
def round_to_15_minutes(t)
rounded = Time.at((t.to_time.to_i / 900.0).round * 900)
t.is_a?(DateTime) ? rounded.to_datetime : rounded
end

The function converts the input to a Time object, which can be converted to the seconds since the epoch with to_i (this automatically strips nano-/milliseconds). Then we divide by 15 minutes (900 seconds) and round the resulting float. This automatically rounds the time to the nearest 15 minutes. Now, we just need to multiply the result by 15 minutes and convert it to a (date)time again.

Example values:

round_to_15_minutes Time.new(2013, 9, 13, 0, 7, 0, "+02:00")
#=> 2013-09-13 00:00:00 +0200
round_to_15_minutes Time.new(2013, 9, 13, 0, 8, 0, "+02:00")
#=> 2013-09-13 00:15:00 +0200
round_to_15_minutes Time.new(2013, 9, 13, 0, 22, 29, "+02:00")
#=> 2013-09-13 00:15:00 +0200
round_to_15_minutes Time.new(2013, 9, 13, 0, 22, 30, "+02:00")
#=> 2013-09-13 00:30:00 +0200
round_to_15_minutes DateTime.now
#=> #<DateTime: 2013-09-13T01:00:00+02:00 ((2456548j,82800s,0n),+7200s,2299161j)>

How do get a random DateTime rounded to beginning of hour in Rails?

I finally found what I was looking for. @Stoic's answer is very good but I found this available method (http://api.rubyonrails.org/classes/DateTime.html):

rand(1.year).ago.beginning_of_hour

Does exactly the same thing but looks neater and prevents you from having to write your own function.

Rounding numbers in ruby up or down to nearest 10 / 100 / 1000 in a different way

It’s not possible to handle the input as you want with the generic rounding method because of contradictory rules (you want 51 to be “rounded” to 100 and others floored down.)

I would go with producing a hash or Range → Price pairs:

rounds = {
(0..50) => 50,
(51..110) => 100,
(111..165) => 150,
(166..220) => 200,
...
(700..1200) => 1000,
(1201..1600) => 1500,
...
(4200..7000) => 5000
}

and then just do detect:

rounds.detect { |range, _| range === price }.last

Round to the nearest half an hour or hour in ruby fake time?

You can extend the time class with this method
I normally do this in the lib/core_ext directory

# lib/core_ext/time.rb
class Time
def round_off(seconds = 60)
Time.at((self.to_f / seconds).round * seconds)
end
end

now you can do something like

time = Time.zone.now - rand(3).days - rand(2).hours + rand(60).minutes
time.round_off(30.minutes)

I hope that this is able to help you

Python Pandas: Rounding Datetime down to nearest 15 minute and extracting time with NA in the Column

Let's try passing errors='coerce':

df['round_time'] = pd.to_datetime(df['Start_Time'], errors='coerce').dt.floor('15T')

Output:

            Start_Time          round_time
0 2020-01-01 19:43:32 2020-01-01 19:30:00
1 2020-01-11 12:23:12 2020-01-11 12:15:00
2 NaN NaT
3 2020-03-01 06:23:32 2020-03-01 06:15:00

How to round unix timestamp up and down to nearest half hour?

Use modulo.

$prev = 1330518155 - (1330518155 % 1800);
$next = $prev + 1800;

The modulo operator gives the remainder part of division.

How do get a random DateTime rounded to beginning of hour in Rails?

I finally found what I was looking for. @Stoic's answer is very good but I found this available method (http://api.rubyonrails.org/classes/DateTime.html):

rand(1.year).ago.beginning_of_hour

Does exactly the same thing but looks neater and prevents you from having to write your own function.

Ruby on Rails converting Timescale SQL rate code to Ruby

It's possible, but I bet building the same model in Ruby (MRI) will be much slower than over SQL runtime.

Would you mind sharing more details about what performance issues do you have?

If you want to build it with Ruby, I'd say that you should think about having some "window concept" that will be responsible for understanding the lag over some specific array.

Example:

a = [1,2,3,4,5]
lag = -> (i) {a[i-2] if i > 1} # => #<Proc:0x00007fcca6cf6aa0@(pry):12 a.each_with_index.map{|e,i|[e,lag[i]]}
# => [[1, nil], [2, nil], [3, 1], [4, 2], [5, 3]]

In this case, I'm using raw numbers but you can build a more complex rule with objects that contains the time attribute.

You can round time as time_bucket using some simple module around the time. Check some ideas here.



Related Topics



Leave a reply



Submit