使用Ruby从CSV中减去时间

嗨,我想使用Ruby从CSV数组中减去时间

时间[0]是12:12:00 AM
时间[1]是12:12:01 AM

这是我的代码

time_converted = DateTime.parse(time) difference = time_converted[1].to_i - time_converted[0].to_i p difference 

但是,我得到了0

p time[0].to_i给了我12

有没有办法来解决这个问题?

您可以使用Time#strptime来定义已解析字符串的格式。

在您的情况下,字符串是%I:%M:%S%p

  • %I = 12小时时间
  • %M =分钟
  • %S =秒
  • %p = AM / PM指标

所以要解析你的例子:

 require 'time' time = %w(12:12:00AM 12:12:01AM) parsed_time = time.map { |t| Time.strptime(t, '%I:%M:%S%p').to_i } parsed_time.last - parsed_time.first => 1 

使用Ruby DateTime类并将日期解析为该类的对象。