【问题标题】:Subtract Time from CSV using Ruby使用 Ruby 从 CSV 中减去时间
【发布时间】:2018-02-21 03:06:09
【问题描述】:

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

时间[0] 是上午 12:12:00
时间[1] 是上午 12:12:01

这是我的代码

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

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

【问题讨论】:

标签: ruby csv time


【解决方案1】:

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

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

  • %I = 12 小时时间
  • %M = 分钟
  • %S = 秒
  • %p = 上午/下午指示器

所以解析你的例子:

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

【讨论】:

  • 我收到一条错误消息,提示“strptime”的方法未定义。有什么遗漏吗?
  • @JoshuaNg 你必须require 'time'
  • 啊。解决了这个问题。
【解决方案2】:

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

【讨论】:

  • 由于 DateTime 对象一次解析一个字符串,您可能想尝试类似的方法: time_converted = time.map() { |t| DateTime.new(t.to_s) }
  • p time_converted[0] 给我#<DateTime: 0012-01-01T00:00:00+00:00 ((1725441j,0s,0n),+0s,2299161j)> 有没有办法只得到时间?
  • 最终,目标是用 time_converted[0] 减去 time_converted[1]
  • DateTime 类有一个to_time 方法,该方法将返回一个Time 对象。试试看。
  • 来自文档,“如果您需要在历史上下文中处理日期和时间,您将需要使用 DateTime”。对于常规时间解析,您应该使用Time
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-03
  • 2014-08-13
  • 2010-09-19
  • 1970-01-01
  • 2017-05-04
相关资源
最近更新 更多