Search code examples
pythonprometheusgrafanaprometheus-operatorgrafana-api

Set prometheus metric to return datetime instead of a float


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"))

Solution

  • 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