简体   繁体   中英

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?

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

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)>`.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM