我试图用datetime数据类型(标准日期时间格式)计算几行的平均值.
我怎样才能做到这一点?
我想在 Ruby 中获取日期时间列表,然后计算它们之间的天数,然后平均这些日期。这样对吗?有没有更短的方法来做到这一点?
dates = ["2012-08-05 00:00:00 UTC", "2012-06-17 00:00:00 UTC", "2012-06-15 00:00:00 UTC", "2011-06-06 00:00:00 UTC"]
difference = Array.new
dates.each_with_index do |date, index|
if index != 0
difference << date.to_date - dates[index - 1].to_date
end
end
avg = difference.inject{ |sum, el| sum + el }.to_f / arr.size
Run Code Online (Sandbox Code Playgroud)
然后会以天格式输出吗?
如果您愿意,您也可以给我一个 Rails 版本,因为我将从模型字段中提取日期时间。