ruby 공부 - interval단위로 DateTIme 시간 출력하기
ruby 공부를 위해서 작성한 코드(snippet)이다.
ruby date, time을 이해하고, ruby optparse 공부한다.
모듈을 만들어보고 테스트해보았다.
https://gist.github.com/knight1128/c4c75d27e91779e26b5d
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