Search code examples
ruby-on-railsrubydatetimestrptime

Ruby strptime with greater than 24 hours


I have a string of the following format:

"136:16:11.862504" 
(hours:minutes:seconds:milliseconds) 

Whenever I try to use Ruby's strptime to parse this string, it throws an ArgumentError: invalid strptime format - '%H:%M:%S'

I've actually searched quite extensively and cannot figure out an elegant way to parse this (besides the rather clunky solution of splitting the string by its colons and periods, and doing it all manually). Is there a way of doing this that I'm overlooking?

EDIT: I'm not looking to get a timestamp out of this, I'm looking to get a time duration.


Solution

  • What is your expected output? '136' is not a valid hour, and since you don't have a date portion, we can't simply turn those 'extra' hours into days. If you don't care about the date portion, this solution may work for you:

    time = "136:16:11.862504"
    hours, minutes, seconds = time.split(":").map(&:to_f)
    hours %= 24
    minutes %= 60
    seconds %= 60
    
    Time.new(0, 1, 1, hours, minutes, seconds, 0)
    => 0000-01-01 16:16:11 +0000