Question : in ruby how to I subtract time  "12/21/08 17:00:02"  from "12/21/08 17:00:25"


Here is a data file and I want to know how long it takes from Start to Complete for each job.  

I think I need to convert the date / time into something that Ruby can work on easy.  

12/19/08 17:52:58 nsrd: savegroup info: starting  ACME_STD_INCR (with 56 client(s))
12/20/08 00:37:05 nsrd: savegroup alert: ACME_STD_INCR completed, total 56 client(s), 0 Hostname(s) Unresolved, 2 Failed, 54 Succeeded. (nc1crappdev01, www.athleticsupport Failed)
12/20/08 17:00:03 nsrd: savegroup info: starting  ACME_STD_INCR (with 55 client(s))
12/20/08 17:00:49 nsrd: savegroup alert: ACME_STD_INCR completed, total 56 client(s), 1 Hostname(s) Unresolved, 0 Failed, 55 Succeeded.
12/21/08 17:00:02 nsrd: savegroup info: starting  ACME_STD_INCR (with 55 client(s))
12/21/08 17:00:25 nsrd: savegroup alert: ACME_STD_INCR completed, total 56 client(s), 1 Hostname(s) Unresolved, 0 Failed, 55 Succeeded.
12/22/08 17:00:01 nsrd: savegroup info: starting  ACME_STD_INCR (with 54 client(s))
12/23/08 04:42:43 nsrd: savegroup alert: ACME_STD_INCR completed, total 55 client(s), 1 Hostname(s) Unresolved, 2 Failed, 52 Succeeded. (nc1crappdev01d, www.athleticsupport Failed)


Answer : in ruby how to I subtract time  "12/21/08 17:00:02"  from "12/21/08 17:00:25"

here you go
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
require "time"
 
def extract_date(str)
  str.scan(/^(\d+)\/(\d+)\/(\d+)\s*(\d+)\:(\d+)\:(\d+)/) do |mon,day,year,hour,min,sec|
      return Time.utc(year, mon,day,hour,min, sec)
    end
end
 
def split_seconds(s)
  hours = s / 3600
  minutes = (s % 3600) / 60
  seconds = (s % 3600) % 60
  return sprintf("%02d:%02d:%02d", hours.floor, minutes.floor, seconds)
end
 
start = nil
second = nil
 
File.open("subtract-time.txt").each do |record|
  
  if record =~ /starting/ then
    start = extract_date(record)
    second = nil
  elsif record =~ /completed/
    second = extract_date(record)
  end
  
  unless second.nil? then
  puts start
  puts second
  difference = second - start
  puts split_seconds(difference)
  puts "---"
  end
 
 end
Open in New Window Select All
Random Solutions  
 
programming4us programming4us