Skip to content

Commit e2f2bf9

Browse files
authored
Format negative timestamps with one leading sign (#1229)
Signed-off-by: Harshil <181649964+Harshil-1603@users.noreply.github.com> Co-authored-by: Harshil <181649964+Harshil-1603@users.noreply.github.com>
1 parent a6b04c5 commit e2f2bf9

3 files changed

Lines changed: 23 additions & 1 deletion

File tree

‎prometheus_client/samples.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ def __init__(self, sec: float, nsec: float) -> None:
1313
self.nsec: int = int(nsec)
1414

1515
def __str__(self) -> str:
16-
return f"{self.sec}.{self.nsec:09d}"
16+
sign = '-' if self.sec < 0 or self.nsec < 0 else ''
17+
return f"{sign}{abs(self.sec)}.{abs(self.nsec):09d}"
1718

1819
def __repr__(self) -> str:
1920
return f"Timestamp({self.sec}, {self.nsec})"

‎tests/openmetrics/test_exposition.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,8 @@ def collect(self):
492492
metric.add_sample("ts", {"foo": "d"}, 0, Timestamp(123, 456000000))
493493
metric.add_sample("ts", {"foo": "e"}, 0, Timestamp(123, 456000))
494494
metric.add_sample("ts", {"foo": "f"}, 0, Timestamp(123, 456))
495+
metric.add_sample("ts", {"foo": "g"}, 0, Timestamp(-123, 456000000))
496+
metric.add_sample("ts", {"foo": "h"}, 0, Timestamp(-123, 456))
495497
yield metric
496498

497499
self.registry.register(MyCollector())
@@ -503,6 +505,8 @@ def collect(self):
503505
ts{foo="d"} 0.0 123.456000000
504506
ts{foo="e"} 0.0 123.000456000
505507
ts{foo="f"} 0.0 123.000000456
508+
ts{foo="g"} 0.0 -123.456000000
509+
ts{foo="h"} 0.0 -123.000000456
506510
# EOF
507511
""", generate_latest(self.registry, version="1.0.0"))
508512

‎tests/test_samples.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,23 @@
44

55

66
class TestSamples(unittest.TestCase):
7+
def test_negative_timestamp_string(self):
8+
for nsec, expected in [
9+
(0, '-123.000000000'),
10+
(1, '-123.000000001'),
11+
(456000000, '-123.456000000'),
12+
(999999999, '-123.999999999'),
13+
]:
14+
with self.subTest(nsec=nsec):
15+
timestamp = samples.Timestamp(-123, nsec)
16+
self.assertEqual(str(timestamp), expected)
17+
self.assertEqual(float(str(timestamp)), float(timestamp))
18+
19+
def test_negative_timestamp_string_with_zero_seconds(self):
20+
timestamp = samples.Timestamp(-0.5, 500000000)
21+
self.assertEqual(str(timestamp), '-0.500000000')
22+
self.assertEqual(float(str(timestamp)), float(timestamp))
23+
724
def test_gt(self):
825
self.assertEqual(samples.Timestamp(1, 1) > samples.Timestamp(1, 1), False)
926
self.assertEqual(samples.Timestamp(1, 1) > samples.Timestamp(1, 2), False)

0 commit comments

Comments
 (0)