部門 > Ruby > GPXファイルをRubyで扱う > GPXの時間をUnix timeに変換する

GPXの時間表記はコンピューターだと扱いにくいので,Unix時間に変換したい。今のところ,緯度と経度のところにUnix時間を追加するようにはできた。これによって,例えば時間でカットをかけたり,時間平均をとったりできる。
#!/usr/bin/ruby
# -*- coding: utf-8 -*-
require "rexml/document"
 
in_file_name = "e101.gpx"
out_file_name = "e101_unix.gpx"
 
#start_time = 0
#stop_time = 1314540864
 
doc = nil
File.open(in_file_name) {|xmlfile|
  doc = REXML::Document.new(xmlfile)
}
 
# http://www6.airnet.ne.jp/manyo/xml/ruby/step10.html
 
trkseg = doc.elements["/gpx/trk/trkseg"]
trkseg.elements.each("trkpt"){|trkpt|
  #  longtitude = trkpt.attributes.get_attribute("lon")
  #  latitude = trkpt.attributes.get_attribute("lat")
  trkpt.elements.each("time"){|nyaa|
    time = nyaa.text#.to_f
 
    year = time[0..3]
    month = time[5..6]
    day = time[8..9]
    hour = time[11..12]
    minute = time[14..15]
    second = time[17..18]
 
    unixtime = Time.local(year,month,day,hour,minute,second).to_i
    trkpt.add_attribute("unixtime","#{unixtime}")
 
#    p unixtime
 
 
=begin  時間でカットをかける。ちゃんと動く   
    if unixtime < start_time
      trkseg.delete_element(trkpt)
    end
    if unixtime > stop_time
      trkseg.delete_element(trkpt)
    end
=end
 
    }}
 
  File.open(out_file_name,"w") do |outfile|
    doc.write(outfile, 0)
  end
 

タグ:

Ruby XML
最終更新:2011年10月24日 19:09