Set prometheus metric to return datetime instead of a float

935 views Asked by At
self.add_metric(
            prom.Gauge,
            "date_to_catch",
            "The timestamp when the event happened",
        )
@property
    def date_to_catch(self):
        return self.get_metric("date_to_catch")

def get_the_date(self):
self.date_to_catch.set(datetime.now().timestamp())

I would like that the metric is returning a datetime instead of a timestamp. I know that metric.set() returns a float, how can I force/hack it to return a datetime? I have tried this but it was showing an error since the retun should be float:

self.date_to_catch.set(datetime.fromtimestamp(datetime.now().timestamp()).replace(microsecond=0).strftime("%c"))
2

There are 2 answers

4
markalex On BEST ANSWER

Prometheus' metric can take as values only numbers. And I believe in your situation metric with the value of UNIX timestamp is perfectly fine.

Then, you can simply configure your panel to show this value as time.

For example, this can be done with Transformation Convert field type. It will convert timestamp in milliseconds into human readable date time.

Example of query timestamp(up) * 1000 (multiplication by 1000 to convert timestamp in seconds into timestamp in milliseconds): enter image description here

6
Ömer Sezer On

You can only send the string date time with labels of the metrics. Values only can be integer or float. But, if you send it with the label, you can see the human-readable date time.

Defining metrics with readable date time label:

custom_metric = Gauge(
    "custom_metric_data",
    "custom metric data as a metric",
    ["data", "readable_datetime"]
)

Adding the human readable date time into the metric label + sending float unix timestamp:

from datetime import datetime
import time

def get_current_unix_timestamp():
  return float(time.time())

now = datetime.now().strftime("%Y-%m-%dT%H:%M:%S%z")

# Set the metric value with labels + value is unixtimestamp in float
custom_metric.labels(data=data, readable_datetime=now).set(get_current_unix_timestamp())

Metric Output on Prometheus Exporter:

custom_metric{data="data",readable_datetime="2023-10-17T10:49:18"} 1.697532558e+09