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")series string for this time argumentFormatted calendar stringOn-chart dashboard timestamps and alert payloads

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

The script gates entry signals by bar-open time in a half-open UTC interval: start included, end excluded. Its weekday filter also uses UTC. This is not an exact fill-time boundary: under default strategy settings, orders normally fill on a later tick, and an end-of-window close is requested only when the script next calculates on a bar outside the interval. Disabling Friday entries does not close an existing position for the weekend.

Pine Script v6: UTC entry-date and weekday filterpinescript
//@version=6
strategy("Date Range & Session Filter [v6]", 
         overlay = true, 
         initial_capital = 10000, 
         default_qty_type = strategy.percent_of_equity, 
         default_qty_value = 10)

// Explicit UTC dates; end is exclusive.
int startTimestamp = input.time(timestamp("01 Jan 2024 00:00 +0000"), "Start (inclusive)")
int endTimestamp = input.time(timestamp("01 Jan 2027 00:00 +0000"), "End (exclusive)")
if startTimestamp >= endTimestamp
    runtime.error("Start must precede end")

// Day of week filters
bool tradeMonday = input.bool(true, "Trade Monday")
bool tradeFriday = input.bool(false, "Allow Friday entries (UTC)")

// Gate signals by bar-open time, not order-fill time.
bool inDateRange = time >= startTimestamp and time < endTimestamp
int utcDay = dayofweek(time, "UTC")
bool isMonday = utcDay == dayofweek.monday
bool isFriday = utcDay == 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: time(timeframe.period, "0930-1600:23456", "America/New_York") tests a Monday–Friday session in New York time. Session strings are custom windows, not an exchange holiday calendar; align boundaries with chart bars.

Common timestamp traps in strategy backtesting

Avoid these subtle date and timing mistakes:

  • Timestamp overloads: Numeric calendar arguments use the exchange timezone unless a zone is supplied; the date-string overload defaults to UTC when no zone is included. The chart display timezone does not change script calculations.
  • 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. Compare historical tests with explicit date inputs and costs. Selecting favorable dates can overfit; validate on a separate period.

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