Skip to content

Commit 7393617

Browse files
committed
add InfluxDB.convert_timestamp utility
1 parent cf93ad7 commit 7393617

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

lib/influxdb.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
require "influxdb/max_queue"
55
require "influxdb/point_value"
66
require "influxdb/config"
7+
require "influxdb/timestamp_conversion"
78

89
require "influxdb/writer/async"
910
require "influxdb/writer/udp"
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
module InfluxDB #:nodoc:
2+
TIMESTAMP_CONVERSIONS = {
3+
"ns" => 1e9.to_r,
4+
nil => 1e9.to_r,
5+
"u" => 1e6.to_r,
6+
"ms" => 1e3.to_r,
7+
"s" => 1.to_r,
8+
"m" => 1.to_r / 60,
9+
"h" => 1.to_r / 60 / 60,
10+
}.freeze
11+
private_constant :TIMESTAMP_CONVERSIONS
12+
13+
# Converts a Time to a timestamp with the given precision.
14+
#
15+
# `convert_timestamp(Time.now, "ms")` might return `1543533308243`.
16+
def self.convert_timestamp(time, time_precision)
17+
factor = TIMESTAMP_CONVERSIONS.fetch(time_precision.to_s) do
18+
raise "Invalid time precision: #{time_precision}"
19+
end
20+
21+
(time.to_r * factor).to_i
22+
end
23+
end
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
require "spec_helper"
2+
3+
RSpec.describe InfluxDB do
4+
describe ".convert_timestamp" do
5+
let(:sometime) { Time.parse("2017-12-11 16:20:29.111222333 UTC") }
6+
7+
{
8+
"ns" => 1_513_009_229_111_222_333,
9+
nil => 1_513_009_229_111_222_333,
10+
"u" => 1_513_009_229_111_222,
11+
"ms" => 1_513_009_229_111,
12+
"s" => 1_513_009_229,
13+
"m" => 25_216_820,
14+
"h" => 420_280,
15+
}.each do |precision, converted_value|
16+
it "should return the timestamp in #{precision.inspect}" do
17+
expect(described_class.convert_timestamp(sometime, precision)).to eq(converted_value)
18+
end
19+
end
20+
21+
it "should raise an excpetion when precision is unrecognized" do
22+
expect { described_class.convert_timestamp(sometime, "whatever") }
23+
.to raise_exception(/invalid time precision.*whatever/i)
24+
end
25+
end
26+
end

0 commit comments

Comments
 (0)