Hi, welcome to Word of Mike, my little corner of the internet. I am a Software/Web Developer working in North Yorkshire. I mainly write about programming but my other passion is politics so beware. (click to hide)

2013-09-02 10:20:08 UTC

Parsing Time Duration Strings to Milliseconds in Ruby


I'm writing a parser (read: screen scraper) for horse racing data and part of it is parsing the winning times, which I scrape in the format: "1m 12.72s". Thus, I wrote this simple one-liner (kind of) to convert that into milliseconds that I can then store in my db as an integer.

UNITS_IN_MS = {
  'd' => 86400000,
  'h' => 3600000,
  'm' => 60000,
  's' => 1000
}

time = "1m 12.72s"
 => "1m 12.72s"
time.scan(/(\d+(?:\.\d+)?)([ms])/).map{|n, unit| n.to_f*UNITS_IN_MS[unit]}.reduce(:+).to_i
 => 72720

As you can see, it scans the string using regex and returns an array like: [["1", "m"], ["12.72", "s"]], which we then map to an array of each time part in milliseconds, using our hash to lookup the millisecond equivalent of the units, reduce using addition to get our total, and finally convert it to an integer.

Included hours and days because you never know with some of the donkeys I end up betting on.