FAQ

How to Add / Subtract Time in Pine Script

How to Add / Subtract Time in Pine Script

Representing time and date in Pine Script can be problematic, especially for not-so-experienced developers. The output format for date/time may not make a lot of sense. As an illustration, let’s try to plot the date/time on your screen using the following code.

//@version=5
indicator("My Script")

t = timestamp("01 Jan 2022 00:00")

if barstate.islast 
    label.new(bar_index, high, str.tostring(t))

You should get something like this:

This happens because date and time are represented in the Unix format (the amount of milliseconds passed from 01 Jan 1970).

Using Mathematical Operations to Add/Subtract Dates

Pine Script does not provide native functions to compute dates by simply adding or subtracting a certain amount of time. However, we can still accomplish that by using simple mathematical operations. The idea is to declare date/time values as integer data types so we can easily compute dates by adding or subtracting milliseconds.

→ Multiples Table

Here is a small table with a multiple you need to add for every date element:

Date ElementMultiple of Milliseconds 
1 millisecond1
1 second1000
1 minute60000
1 hour 3600000
1 day86400000
1 week 604800000

→ Sample Date/Time Operations

Here are some examples I created to demonstrate how you can use basic mathematical operations to compute dates (using milliseconds).

Add 1 day:

t2 = t1 + 86400000

Subtract 3 hours:

t3 = t1 – 3 * 3600000

Add 37 seconds:

t4 = t1 + 37 * 60000

Subtract 2 weeks:

t5 = t1 – 2 * 604800000


Follow me on TradingView and YouTube.

This image has an empty alt attribute; its file name is wide.png
Pine Script Programming Courses
Pine Script Programming Courses
Learn to build your own TradingView Indicators and Strategies
Sidebar Signup Form
If you want to be the first in this business, subscribe to the latest news