Created
March 24, 2013 21:44
-
-
Save roelentless/5233676 to your computer and use it in GitHub Desktop.
A method to group time ranges into time-by-day percentages.
Usefull for analysis of time ranges.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
# Having two times, group the time by dates in percentages. | |
# Time and analysis will be done in the timezone the time is passed with. | |
# Result for time range D1-D5: | |
# D1 |-----D2------------D3------------D4------| D5 | |
# 16.67% 32.34% 32.34% 16.67% | |
def date_range_group(start_time, end_time) | |
return nil unless start_time | |
return nil unless end_time > start_time | |
total = end_time - start_time | |
pct = 100/total | |
dates = {} | |
start_of_day = nil | |
start_of_next_day = nil | |
begin | |
if not start_of_day | |
start_of_day = start_time | |
else | |
start_of_day = start_of_next_day | |
end | |
start_of_next_day = start_of_day.change(:hour=>23).change(:min=>59).change(:sec=>59)+1 | |
if(start_of_next_day > end_time) | |
start_of_next_day = end_time | |
end | |
time_in_day = start_of_next_day - start_of_day | |
dates[start_of_day.to_i] = {:date => time_in_day, :pct => (time_in_day*pct)} | |
end while start_of_next_day < end_time | |
# Here we have our distribution | |
dates | |
end | |
# Example | |
t1 = Time.now - (3.5 * 86400) | |
t2 = Time.now | |
print date_range_group(t1, t2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment