尝试救援块中的第一个错误后,Rails 4.0.0 to_time总是失败

时间:2013-08-16 17:20:32

标签: ruby-on-rails

我正在尝试使用to_time使用以下代码解析指纹识别器的xml文件。在第一个错误之后,每次读取都是错误的。错误之前有数百个正确读取的条目,错误之后有数百个也是错误,即使先前正确解析了相同的格式。我猜测12:03 AM字符串触发了错误。

attendances_file = params[:attendances_file].read

 doc = Nokogiri::XML(attendances_file) do |config|
        config.strict.nonet
      end

  attendances = doc.xpath("//ROW")

  attendances.each do |attendance|

  pin = attendance.get_attribute('Pin').to_i

     begin
      attendance_datetime = attendance.get_attribute('sTime').to_time

      logger.info pin.to_s
      logger.info attendance_datetime.to_s

      rescue      
      logger.info attendance.get_attribute('Pin')
      logger.info 'ERROR ' + attendance.get_attribute('sTime') 
      end

以下是xml文件的片段

<ROW Pin="138" Name="138" sTime="8/12/2013 8:14 PM" VerifyFlag="Fingerpint" MachineName="Office" Abnormite=""/>
<ROW Pin="142" Name="142" sTime="8/12/2013 8:14 PM" VerifyFlag="Fingerpint" MachineName="Office" Abnormite=""/>
<ROW Pin="163" Name="163" sTime="8/12/2013 8:16 PM" VerifyFlag="Fingerpint" MachineName="Office" Abnormite=""/>
<ROW Pin="103" Name="103" sTime="8/13/2013 12:03 AM" VerifyFlag="Fingerpint" MachineName="Office" Abnormite=""/>
<ROW Pin="101" Name="101" sTime="8/13/2013 12:03 AM" VerifyFlag="Fingerpint" MachineName="Office" Abnormite=""/>
<ROW Pin="401" Name="401" sTime="8/13/2013 12:36 AM" VerifyFlag="Fingerpint" MachineName="Office" Abnormite=""/>
<ROW Pin="505" Name="505" sTime="8/13/2013 2:17 AM" VerifyFlag="Fingerpint" MachineName="Office" Abnormite=""/>
<ROW Pin="321" Name="321" sTime="8/13/2013 2:35 AM" VerifyFlag="Fingerpint" MachineName="Office" Abnormite=""/>
<ROW Pin="322" Name="322" sTime="8/13/2013 2:35 AM" VerifyFlag="Fingerpint" MachineName="Office" Abnormite=""/>

以下是日志中的相同代码段

138
2013-12-08 20:14:00 +0800

142
2013-12-08 20:14:00 +0800

163
2013-12-08 20:16:00 +0800

103
ERROR 8/13/2013 12:03 AM

101
ERROR 8/13/2013 12:03 AM

401
ERROR 8/13/2013 12:36 AM

505
ERROR 8/13/2013 2:17 AM

321
ERROR 8/13/2013 2:35 AM

322
ERROR 8/13/2013 2:35 AM

1 个答案:

答案 0 :(得分:0)

“错误”是因为String#time为所有ArgumentError值抛出sTime,其中间值(即以下字符串中的13)大于12(月):< / p>

8/13/2013 12:03 AM

因此,此处的解决方案是使用DateTime#strptime指定您的格式,如下所示:

begin
  s_time = attendance.get_attribute('sTime')
  attendance_datetime = DateTime.strptime(s_time, "%m/%d/%Y %l:%M %p")
  ...
rescue
  ...
end