Time and Date Functions
You'll learn how to filter and manipulate metrics using Prometheus's time and date functions to query data based on specific time windows or days.
Why Time Functions Matter
When analyzing metrics, you often need to filter data by time of day, day of week, or align timestamps precisely. Prometheus provides built-in functions to work with temporal data, making it easy to answer questions like "What was CPU usage every Monday at 3 PM?" or "Show me errors that occurred in the last hour of each day."
Core Time Functions
time()
Returns the current Unix timestamp (seconds since epoch) as a floating-point number. This is useful for calculating relative time or creating dynamic queries:
time() - my_metric_timestamp
This calculates how many seconds ago a metric was recorded.
day_of_week()
Extracts the day of week from a timestamp, returning 0 (Sunday) through 6 (Saturday). Perfect for filtering weekday vs. weekend patterns:
day_of_week() == 1 # Monday
You can combine this with metrics to analyze behavior on specific days.
timestamp()
Returns the timestamp of each sample in a vector. Unlike time(), which gives the query evaluation time, timestamp() shows when the actual data point was recorded:
timestamp(http_requests_total)
Practical Filtering Example
http_requests_total{status="500"}
and day_of_week() >= 1
and day_of_week() <= 5
This filters server errors that occurred only on weekdays.
Key Takeaway: Use time() for current evaluation time, day_of_week() to filter by calendar day, and timestamp() to inspect when samples were actually collected—enabling powerful temporal analysis of your metrics.