"2015-12-05T07:49:30.000Z", "endTime"=>"2015-12-05T-6ren">
gpt4 book ai didi

arrays - 从哈希数组计算平均时间

转载 作者:太空宇宙 更新时间:2023-11-03 17:31:39 25 4
gpt4 key购买 nike

我正在尝试从哈希数组计算平均时间。这是数组。

array = [
{"startTime"=>"2015-12-05T07:49:30.000Z", "endTime"=>"2015-12-05T15:56:30.000Z"},
{"startTime"=>"2015-12-04T07:02:30.000Z", "endTime"=>"2015-12-04T14:59:30.000Z"},
{"id"=>"5660614e8a3b090700bad845", "userId"=>"55cd59542d98600100397c12", "day"=>"2015-12-03", "startTime"=>"2015-12-03T06:02:32.000Z", "endTime"=>"2015-12-03T13:38:32.000Z"},
{"startTime"=>"2015-12-02T09:17:33.000Z", "endTime"=>"2015-12-02T15:27:33.000Z"},
{"startTime"=>"2015-12-01T05:45:36.000Z", "endTime"=>"2015-12-01T13:50:36.000Z"}
]

我正在尝试获取平均开始时间和结束时间。到目前为止,这是我尝试过的方法。

avg = Time.at(array.map {|x| x['startTime']}.reduce(:+).to_f / array.size.to_i)

我得到的结果是 1969-12-31 16:06:43 -0800。这是不正确的。

最佳答案

require 'time'

array = [
{"startTime"=>"2015-12-05T07:49:30.000Z", "endTime"=>"2015-12-05T15:56:30.000Z"},
{"startTime"=>"2015-12-04T07:02:30.000Z", "endTime"=>"2015-12-04T14:59:30.000Z"},
{"id"=>"5660614e8a3b090700bad845", "userId"=>"55cd59542d98600100397c12", "day"=>"2015-12-03", "startTime"=>"2015-12-03T06:02:32.000Z", "endTime"=>"2015-12-03T13:38:32.000Z"},
{"startTime"=>"2015-12-02T09:17:33.000Z", "endTime"=>"2015-12-02T15:27:33.000Z"},
{"startTime"=>"2015-12-01T05:45:36.000Z", "endTime"=>"2015-12-01T13:50:36.000Z"}
]

times = array.map{|el| el['startTime']}.map{|el| Time.parse(el) }
#=> [2015-12-05 07:49:30 UTC, 2015-12-04 07:02:30 UTC, 2015-12-03 06:02:32 UTC, 2015-12-02 09:17:33 UTC, 2015-12-01 05:45:36 UTC]

average_time = Time.at(times.map(&:to_f).inject(:+) / times.size)
#=> 2015-12-03 08:11:32 +0100

关于arrays - 从哈希数组计算平均时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34166625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com