views:

492

answers:

2

I have a number of CSV files which contain start and finish times. I can use FasterCSV to parse the files, but I don't know the best way to get the duration in Ruby. Here are the values in my hash generated for each row of the CSV files.

start time: Mon Jul 20 18:25:17 -0400 2009
end time: Mon Jul 20 18:49:43 -0400 2009
+2  A: 

Not sure if it is the "best" but you can use e.g. DateTime class for this:

require 'date'

d1 = DateTime.parse("Mon Jul 20 18:25:17 -0400 2009")
d2 = DateTime.parse("Mon Jul 21 18:25:17 -0400 2009")

puts "Duration is #{(d2-d1).to_f} days"
Andrew Y
While the DateTime class is OK, there's also '`time.rb`' which extends the standard Time class. It doesn't deal with ambiguity and doesn't support different calendars, so it is much lighter. The syntax is the same (`Time.parse()`)
hhaamu
Addendum: t2 - t1 returns the interval in seconds.
hhaamu
Maybe. I just tend to use DateTime because it looks to be more clever about what it does than Time, and that's the biggest point for me when I'm choose Ruby vs. some other language.
Andrew Y
+2  A: 

You can get the duration by subtracting one DateTime from another. You'll get DateTime objects from FasterCSV as long if you include the :date_time converter. For example:

FasterCSV.foreach(some_file, :converters => [:date_time]) do |row|
    #blah
end

Or, you could just convert them yourself using DateTime#parse.

From there, you can use Date#day_fraction_to_time to get an array containing [hours, minutes, seconds, fraction_of_a_second], which I think is easier to work with than just the fraction of the day.

Depending on how you want to display them, there's probably information that will help you in the answers of this question. Those answers are for Rails, but you can always include the necessary parts from Rails, or just look at the source of the functions (available in the Rails documentation) to see how they do it. It's fairly self-explanatory.

Pesto