1

我有许多包含开始和结束时间的 CSV 文件。我可以使用 FasterCSV 来解析文件,但我不知道在 Ruby 中获取持续时间的最佳方法。这是为 CSV 文件的每一行生成的哈希值。

start time: Mon Jul 20 18:25:17 -0400 2009
end time: Mon Jul 20 18:49:43 -0400 2009
4

2 回答 2

3

不确定它是否是“最好的”,但您可以为此使用 DateTime 类:

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"
于 2009-07-23T18:45:41.177 回答
2

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.

于 2009-07-23T19:07:19.683 回答