Search code examples
ruby-on-railsrubystrptime

How to use strptime to convert timestamp string with milliseconds to time object


I need to use strptime to convert a timestamp string with milliseconds to a Time object.

A work around is using parse:

t= Time.parse('29 Sep 2013 12:25:00.367')
=> 2013-09-29 12:25:00 -0400

But it is very important for my code to use strptime, because I want to be able to pass multiple types of format including: "HH:MM", "HH", etc. through the function.

I can do it with nanoseconds like this:

Time.strptime("12:34:56:789434", "%H:%M:%S:%N")
=> 2016-03-16 12:34:56 +0100

I want something like this:

Time.strptime("12:34:56:789", "%H:%M:%S:%[insert magic letter that represent milliseconds]")

My thought is that there must be a way to do it with milliseconds as well.

Is it possible and how?


Solution

  • Try %L.

    Refer to Ruby's DateTime documentation.