Pine Script Time & Date

Pine Script Timestamp: Time Functions, Date Filters & Session Windows

In Pine Script, the timestamp() function generates a UNIX timestamp in milliseconds for a designated date, time, and timezone. It is commonly used to restrict backtest date ranges and evaluate session trading windows. Pine Script also provides calendar extraction functions like dayofweek, year, month, and hour, alongside str.format_time() to format timestamps into readable date strings.

Build Time Filters with AI

Working with dates, times, and day of week in Pine Script v6

Time handling in TradingView operates in UNIX epoch milliseconds. Understanding time built-ins allows developers to build date-bounded backtests, session break indicators, and calendar-filtered strategies.

Function / Built-inReturned data typeValue formatPractical application
timestamp(2026, 1, 1, 0, 0)simple intUNIX millisecondsSetting backtesting start and end dates
timeseries intUNIX milliseconds of bar openTesting if current candle is inside active trading hours
dayofweekseries int1 (Sunday) to 7 (Saturday)Skipping trading on Fridays or filtering Monday opens
str.format_time(time, "yyyy-MM-dd HH:mm Z")simple / series stringFormatted calendar stringOn-chart dashboard timestamps and alert payloads

Complete Pine Script v6 script: Date window filter & day-of-week strategy

The following script demonstrates how to construct user-selectable start and end date inputs to restrict backtesting execution to an exact historical window, while filtering out trades on specific days of the week.

Pine Script v6: Date range filter and trading session managerpinescript
//@version=6
strategy("Date Range & Session Filter [v6]", 
         overlay = true, 
         initial_capital = 10000, 
         default_qty_type = strategy.percent_of_equity, 
         default_qty_value = 10)

// Date filter inputs using timestamp input type
int startYear = input.int(2024, "Start Year", minval = 2000)
int startMonth = input.int(1, "Start Month", minval = 1, maxval = 12)
int startDay = input.int(1, "Start Day", minval = 1, maxval = 31)

int endYear = input.int(2026, "End Year", minval = 2000)
int endMonth = input.int(12, "End Month", minval = 1, maxval = 12)
int endDay = input.int(31, "End Day", minval = 1, maxval = 31)

// Day of week filters
bool tradeMonday = input.bool(true, "Trade Monday")
bool tradeFriday = input.bool(false, "Trade Friday (Weekend Risk Filter)")

// Construct timestamps
int startTimestamp = timestamp("UTC", startYear, startMonth, startDay, 0, 0)
int endTimestamp = timestamp("UTC", endYear, endMonth, endDay, 23, 59)

// Evaluate whether current bar is within active test window
bool inDateRange = time >= startTimestamp and time <= endTimestamp

// Evaluate day-of-week eligibility
bool isMonday = dayofweek == dayofweek.monday
bool isFriday = dayofweek == dayofweek.friday
bool validDay = (not isMonday or tradeMonday) and (not isFriday or tradeFriday)

// Technical signals
float fastEma = ta.ema(close, 20)
float slowEma = ta.ema(close, 50)
bool buySignal = ta.crossover(fastEma, slowEma)
bool exitSignal = ta.crossunder(fastEma, slowEma)

// Execution inside allowed window
if inDateRange and validDay
    if buySignal
        strategy.entry("Long", strategy.long)

if exitSignal or (time > endTimestamp and strategy.position_size > 0)
    strategy.close("Long", comment = "Exit Trigger / Window End")

// Plot moving averages
plot(fastEma, "Fast EMA", color = color.blue)
plot(slowEma, "Slow EMA", color = color.orange)

// Background highlight for active backtest date window
bgcolor(inDateRange ? color.new(color.blue, 95) : na)

Formatting timestamps for webhook alerts and logs

When connecting TradingView to external webhook services or discord bots, timestamps must often match strict ISO or formatted string standards:

  • str.format_time syntax: str.format_time(time, "yyyy-MM-dd HH:mm:ss", "UTC") formats the current bar timestamp into a standardized timestamp string.
  • Timezone support: You can specify explicit IANA timezones such as "America/New_York", "Europe/London", or "UTC" in both timestamp() and str.format_time().
  • Time offset calculations: Because timestamps are expressed in milliseconds, adding one hour to a timestamp is achieved by adding 60 * 60 * 1000.
  • Session functions: For intraday trading windows, the time(timeframe.period, "0930-1600") function returns na outside specified market hours.

Common timestamp traps in strategy backtesting

Avoid these subtle date and timing mistakes:

  • Timezone misalignment: Failing to specify timezones can cause date filters to open or close several hours earlier or later than expected based on exchange local time.
  • Month indexing: In Pine Script timestamp(), January is month 1 and December is month 12 (unlike JavaScript where month is zero-indexed).
  • Day of week numbering: Sunday is 1, Monday is 2, ..., Saturday is 7. Using dayofweek constants like dayofweek.monday prevents index confusion.
Where Pineify fits

Pine Script AI Coding Agent

Generate backtest date filters, intraday session logic, and formatted webhook alert timestamps in Pine Script v6 with Pineify AI.

Also useful: Strategy Optimizer. Evaluate strategy performance across specific calendar years and isolate bullish or bearish market cycles.

Build Time Filters with AI

Frequently asked questions

Date range filtering modifies backtesting sample sizes and statistical significance. Ensure your testing periods encompass both trending and ranging market cycles before deploying live capital.

Sources and verification