Chhabilal
Chhabilal

Reputation: 1104

Ruby Date Time Subtraction

I am trying to calculate the exact duration a process took from some log file result. After parsing the log, I reached at the following stage:

my_array = ["Some_xyz_process", "Start", "2018-07-12", "12:59:53,397", "End", "2018-07-12", "12:59:55,913"]

How can I subtract the start date and time from the end date and time in order to retrieve the exact duration the process took?

Upvotes: 1

Views: 843

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110755

my_array = ["Some_xyz_process",
            "Start", "2018-07-12", "12:59:53,397",
            "End", "2018-07-12", "12:59:55,913"]

require 'date'

fmt = '%Y-%m-%d%H:%M:%S,%L'
is = my_array.index('Start')
  #=> 1
ie = my_array.index('End') 
  #=> 4
DateTime.strptime(my_array[ie+1] + my_array[ie+2], fmt).to_time -
DateTime.strptime(my_array[is+1] + my_array[is+2], fmt).to_time
  #=> 2.516 (seconds)

See DateTime#strptime and DateTime# (the latter for format directives). As long as the date and time formats are known I always prefer strptime to parse. Here's an example of why:

DateTime.parse 'Theresa May has had a bad week over Brexit'
  #=> #<DateTime: 2018-05-01T00:00:00+00:00 ((2458240j,0s,0n),+0s,2299161j)>`.

Upvotes: 1

Subash
Subash

Reputation: 3168

You can concat the date and time field and use Time.parse to convert it to a time object and then calculate the difference in number of seconds

Time.parse('2018-07-12 12:59:55,397').to_i - Time.parse('2018-07-12 12:59:53,913').to_i

Hope this helps

Upvotes: 1

Related Questions