How to convert customer interval variable to seconds

Hi Community member,

I have a interval variable by name “period” and its possible values are 1m, 10m, 30m, 1h.

I want to use the same variable and pass it to prometheus query, however, Before passing i need to convert it into “seconds” (For example if i select 1m it want to pass as 60 in the prometheus query)

Best
Grafana Newbie

You can try the workaround below (crappy way to do it, would be nice to have what you ask as a feature in Grafana by adding _s to the variable or something like this)

Create a new variable “period_s” below the “period” variable of type Query on your Prometheus datasource and use this as your expression:

query_result(label_replace(label_replace(label_replace(label_replace(vector(1),"period_s","${period}","",""),"period_s","(60*$1)","period_s","([0-9]+)m"),"period_s","(3600*$1)","period_s","([0-9]+)h"),"period_s","(86400*$1)","period_s","([0-9]+)d"))

Then filter with a standard regex:

/^.*period_s="([^"]+)".*$/

This will use several label_replace on a dummy vector(1) query on your Prometheus datasource to generate the string representing the arithmetic expression you need to have the interval converted to seconds. You can then use the period_s Grafana variable in your prometheus queries (note that as this generates a string representing an arithmetic expression it cannot be used in Grafana attributes such as min step or others)

1 Like

This was very helpful. Thanks.

The regex in the solution has to be modified to work with later versions of Grafana (I suspect 7.4+ when support for named text and value capture groups was added). If you don’t specify “value” as the name of the capture group, the result will include a name and a value separated by whitespace. The name will be the unfiltered string, and the value will be a number that is not even close to the expected value.

This worked correctly for me:

/^.*period_s="(?<value>[^"]+)".*$/