0

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?

sawa
  • 165,429
  • 45
  • 277
  • 381
Marco
  • 15,101
  • 33
  • 107
  • 174
  • Your time seems to be wrong. Somehow, `147` is interpreted as milliseconds, not nanoseconds. – sawa Oct 04 '17 at 06:16
  • 1
    @sawa `%N` parses fractional seconds, i.e. `147` is interpreted as 0.147 seconds. – Stefan Oct 04 '17 at 10:04
  • 1
    @marco what's your expected result? – Stefan Oct 04 '17 at 10:55
  • @Stefan That is what I am pointing out. And I think the OP intended that part to be interpreted as nanoseconds since the documentation says `%N` is defaulted to the 9th decimal place. – sawa Oct 04 '17 at 19:19

2 Answers2

4

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.

sawa
  • 165,429
  • 45
  • 277
  • 381
1

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
lazylead
  • 1,453
  • 1
  • 14
  • 26