time() - Pine Script Function
time()
Section titled “time()”Overview
Section titled “Overview”time() returns the opening timestamp for the bar matching the supplied timeframe and session filter. If the bar falls outside the session or timeframe, the function yields na. This makes it a key building block for custom session highlighting, multi-timeframe logic, and trading windows.
Timestamps are always expressed in milliseconds since 1970-01-01 UTC. Converting to other units requires dividing by 1000 or using str.format_time().
Syntax
Section titled “Syntax”time(timeframe, session, timezone, bars_back) → series intParameters
Section titled “Parameters”| Name | Type | Description |
|---|---|---|
timeframe | series string (optional) | Target resolution. Use "" or timeframe.period to inherit the chart. |
session | series string (optional) | Session filter ("0930-1600", "1000-1100,1400-1500", etc.). Append a timezone after a colon, e.g., "0930-1600:America/New_York". |
timezone | series string (optional) | Override timezone without altering the session string. |
bars_back | series int (optional) | Offset into past bars when building higher-timeframe logic. |
All parameters are optional; omitted values default to the chart’s current settings.
Returns
Section titled “Returns”series int — UNIX time (milliseconds) for the bar open, or na if the bar is outside the specified session.
Remarks
Section titled “Remarks”- Combine with
not na(time(...))to create boolean flags indicating whether the current bar is inside a target session. - Use
timeframe.in_seconds()ortimeframe.multiplierwhen you need numeric comparisons between the chart timeframe and the requested timeframe. - When fetching higher-timeframe timestamps, ensure
timeframeis greater than or equal to the chart timeframe to avoid repeated values.
Example
Section titled “Example”//@version=5indicator("Custom trading window", overlay=true)
sessionInput = input.session("0930-1600", "Trading session")tzInput = input.string("America/New_York", "Session timezone")
inSession = not na(time(timeframe.period, sessionInput + ":" + tzInput))
bgcolor(inSession ? color.new(color.teal, 88) : na, title="Trading session highlight")
plot(close, "Close", color=inSession ? color.white : color.gray)