2012-07-10 43 views
0

我正在研究业务分析应用程序,我需要在特定月份的每小时基础上获取一些数据。例如我想要从2012年6月1日到2012年6月30日的数据,我需要获取这些日子之间每小时的数据。 赞12:00 13:00,13:00-14:00 ....等。ruby​​随着时间的迭代

我该怎么做。请让我知道。使用1.8.7平台。

回答

3

如果您使用Rails有一个日期的方法stephttp://corelib.rubyonrails.org/classes/Date.html#M001273


在纯Ruby只写简单的循环:

t=Time.new(2012,01,01,0,0,0) #start time 
max_time=Time.new(2012,01,31,23,59,59) #end time 
step=60*60 #1hour 
while t<=max_time 
    p t #your code here 
    t += step 
end 

为了简化使用此Ruby扩展:

module TimeStep 

    def step(limit, step) # :yield: time 
    t = self 
    op = [:-,:<=,:>=][step<=>0] 
    while t.__send__(op, limit) 
     yield t 
     t += step 
    end 
    self 
    end 
end 

Time.send(:include, TimeStep) #include the extension 

用法:

t=Time.new(2012,01,01,0,0,0) 
t.step(Time.new(2012,01,31,23,59,59),3600) do |time| 
    puts time 
end 

您还可以向下迭代:

t=Time.new(2012,01,31) 
t.step(Time.new(2012,01,1),-3600) do |time| 
    puts time 
end 
2
start = Date.new(2012, 6, 1).to_time.to_i 
stop = Date.new(2012, 6, 30).to_time.to_i 

(start..stop).step(1.hour).each do |timestamp| 
    puts Time.at(timestamp) 
end 
0

是的,一切都很好!

a = Time.now 
b = Time.now + 3600*8 
(a..b).step(3600){|t| puts t}