Prometheus Time-shifting Functions

Prometheus provides a few time-shifting functions that allow you to shift or offset time series data. These functions help you analyze metrics at different points in time or compare data from different time periods. Here are the main time-shifting functions in PromQL:

1. offset(): The offset() function shifts a time series by a given duration. It takes two parameters: the duration to shift and the input time series. The resulting time series will have its data shifted by the specified duration. This can be useful for comparing data at different time intervals or aligning data from different sources. For example, "offset(5m, my_metric)" shifts the "my_metric" time series 5 minutes into the future.

2. timestamp(): The timestamp() function returns the timestamp of a given point in time. It takes a single parameter, which can be a scalar value or a range vector. The function returns the timestamp corresponding to the provided input. This is useful for extracting specific timestamps from time series data. For example, timestamp(1625200000) returns the timestamp corresponding to the Unix time 1625200000.

These time-shifting functions enable you to manipulate and analyze time series data in Prometheus. They offer flexibility in comparing and aligning metrics at different points in time, extracting specific timestamps, or working with the current time in your queries.

Examples

Here are examples of each time-shifting function in Prometheus:

1. offset():

Suppose you have a metric called request_latency representing the latency of incoming requests. To compare the latency values 10 minutes ago with the current values, you can use the offset() function:

request_latency - offset(10m, request_latency)

This query subtracts the request_latency time series shifted by 10 minutes from the current request_latency time series, giving you the difference in latency between the two time periods.

2. timestamp():

Assume you have a metric called http_requests_total, which represents the total number of HTTP requests made to your server. To retrieve the timestamp of a specific data point, you can use the timestamp() function:

timestamp(http_requests_total{status_code="200"})

This query returns the timestamp corresponding to the latest data point of the http_requests_total time series with a status_code of "200". It helps you identify when a successful HTTP request occurred.