I am trying to parse a fingerprint reader's xml file using to_time using the following code. After the first error, every read is an error. There are many hundreds of correctly read entries before the error and many hundreds after the error which are also errors, even though the same format was previously correctly parsed. I'm guessing that the 12:03 AM string triggered the error.
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
Here is a snippet from the xml file
<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=""/>
Here is the same snippet from the log
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
The "ERROR" is because String#time is throwing an ArgumentError
for all the sTime
values with middle value (ie 13 in the following string) greater than 12 (month):
8/13/2013 12:03 AM
So the solution here would be to use DateTime#strptime
specifying your format as follows:
begin
s_time = attendance.get_attribute('sTime')
attendance_datetime = DateTime.strptime(s_time, "%m/%d/%Y %l:%M %p")
...
rescue
...
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.