Marco
Marco

Reputation: 15909

Convert a time to nanoseconds in Ruby

I have the following time format:

require 'time'

input = "2016-10-04_00.50.31.147"
format = "%Y-%m-%d_%H.%M.%S.%N"

time = Time.strptime(input, format)

How do I get the number of nanoseconds since the epoch?

Upvotes: 1

Views: 5753

Answers (2)

lazylead
lazylead

Reputation: 1979

Try this https://apidock.com/ruby/Time/nsec

t = Time.now        #=> 2007-11-17 15:18:03 +0900
"%10.9f" % t.to_f   #=> "1195280283.536151409"
t.nsec              #=> 536151406

Upvotes: 1

sawa
sawa

Reputation: 168071

This should give you the value:

time.to_f * (10 ** 9)

If you want an integer, apply to_i or whatever to it.

However, notice that your time is wrong, so it would not give the right results.

Upvotes: 4

Related Questions