Ruby Findings

digging for gems

Rational time durations

Posted by Art Green Sat, 10 May 2008 20:41:00 GMT

I needed to write a reporting script the other day that dealt with time durations. The script basically processed a series of log files determining the ‘start’ and ‘end’ times of certain events. Part of the report output needed to be the duration of each event. Calculating this using DateTime objects should have been as easy as this:

def duration
  @end_datetime - @start_datetime
end

Ack, Instead of providing me with something intuitive, I got an object back of class Rational. A fraction of all things:

start = DateTime.parse('2/1/2008 10:35:00')
finish = DateTime.parse('2/1/2008 21:15:00')
duration = finish - start   # => Rational(4, 9)

Well, what the heck do I do with a fraction?

It turns out that Date has a class method called day_fraction_to_time() that takes a Rational and returns the number of hours, minutes, seconds and factions of a section. The beast in action:

start = DateTime.parse('2/1/2008 10:35:00')
finish = DateTime.parse('2/1/2008 21:15:00')
duration = finish - start
Date.day_fraction_to_time(duration)   => [ 10, 40, 0, Rational(0, 1) ]

Joy, this works, I now have my duration in hours minutes and seconds. The only conclusion I can draw regarding using Rational is that it can provide more accuracy than a Double or Float. In other words, it’s a more accurate representation of the percentage of a day since Rational( 1, 3 ) will not lose precision whereas ‘.3333333333’ is only as precise as the number of bytes a floating point number is stored as.

Posted in | no comments |