Created
May 6, 2015 10:32
-
-
Save knight1128/c4c75d27e91779e26b5d to your computer and use it in GitHub Desktop.
print time interval by ruby
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
require 'date' | |
require 'time' | |
require 'optparse' | |
options = {:start_time => nil, :end_time => nil, :interval => nil} | |
parser = OptionParser.new do|opts| | |
opts.banner = "Usage: print-time-interval.rb --time [MIN | HOUR | DAY] --interval [5MIN | HOUR | DAY]" | |
opts.on('-s', '--start_time time', 'time') do |time| | |
options[:start_time] = time; | |
end | |
opts.on('-e', '--end_time time', 'time') do |time| | |
options[:end_time] = time; | |
end | |
opts.on('-i', '--interval interval', 'interval') do |it| | |
options[:interval] = it.downcase; | |
end | |
opts.on('-h', '--help', 'Displays Help') do | |
puts opts | |
exit | |
end | |
end | |
parser.parse! | |
MIN = 60 | |
HOUR = 60 * MIN | |
DAY = 24 * HOUR | |
INTERVAL_5MIN = 5 * MIN | |
INTERVAL_HOUR = 1 * HOUR | |
INTERVAL_DAY = 1 * DAY | |
INTERVAL_DEFAULT = INTERVAL_DAY | |
if options[:start_time] == nil | |
options[:start_time] = '2014-12-30' | |
end | |
if options[:end_time] == nil | |
options[:end_time] = '2015-1-1 1:0:0' | |
end | |
if options[:interval] == nil | |
interval = INTERVAL_DEFAULT | |
end | |
interval_array = ["day", "hour", "5min"] | |
interval_array.each do |it| | |
if (it == options[:interval]) | |
if (it == "day") | |
interval = INTERVAL_DAY | |
elsif (it == "hour") | |
interval = INTERVAL_HOUR | |
elsif (it == "5min") | |
interval = INTERVAL_5MIN | |
end | |
end | |
end | |
if interval == nil | |
interval = INTERVAL_DEFAULT | |
end | |
time_start = Time.parse(options[:start_time]) | |
time_end = Time.parse(options[:end_time]) | |
module TimeStep | |
def step(end_time, incr) | |
t = self | |
while t <= end_time | |
yield t | |
t += incr | |
end | |
end | |
end | |
time_start.extend(TimeStep).step(time_end, interval) do |tick| | |
puts tick.strftime("%Y%m%d%H%M") # | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ ruby test.rb -s '2014-12-30' -e '2015-1-1' -i hour
$ ruby test.rb -s '2014-12-30' -e '2015-1-1' -i day
$ ruby test.rb -s '2014-12-30' -e '2015-1-1' -i 5min