Reputation: 1096
I have a dictionary as such:
{"status": "ok", "data": [{"temp": 22, "datetime": "20160815-0330"}]}
20160815-0330
means 2016-08-15 03:30
. I want to group by day and calculate min and max temp
, but the day should start at 09:00 and end at 08:59. How could I do that?
Here is my code:
@results = @data['data'].group_by { |d| d['datetime'].split('-')[0] }.map do |date, values|
[date, {
min_temp: values.min_by { |value| value['temp'] || 0 }['temp'],
max_temp: values.max_by { |value| value['temp'] || 0 }['temp']
}]
end
#=> {"20160815"=>{:min_temp =>12, :max_temp =>34}}
I works, but the starting point is 00:00, not 09:00.
Upvotes: 0
Views: 44
Reputation: 30473
I would suggest to use a timezone trick:
def adjust_datetime(str)
DateTime.parse(str.sub('-', '') + '+0900').utc.strftime('%Y%m%d')
end
data.group_by { |d| adjust_datetime(d['datetime']) }
Here is an explanation:
str = '20160815-0330'
str = str.sub('-', '') #=> '201608150330'
str = str + '+0900' #=> '201608150330+0900'
dt = DateTime.parse(str) #=> Mon, 15 Aug 2016 03:30:00 +0900
dt = dt.utc #=> 2016-08-14 18:30:00 UTC
dt.strftime('%Y%d%m') #=> '20160814'
Upvotes: 1