Library · Pine Script v6 · Library

Time

by Electrified-Trading· code credited to Electrified

This library provides utilities for measuring time in Pine Script.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code158
Settings0inputs
LicenceMPL-2.0
Last update1 year ago7 Jul 2025

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new library, select all of the template text and paste. Press Save and give it a name.
  4. 4Publish or import itA library draws nothing. Publish it from the editor, then import its functions in your own scripts.

Source Code

158 lines of Pine Script v6 from Time.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

Time.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Electrified

// @version=6
// @description Utilities for measuring time.
library("Time")

///////////////////////////////////////////////////
// CONSTANTS
///////////////////////////////////////////////////

// Time unit strings
const string BARS = "bars"
const string SECONDS = "seconds"
const string MINUTES = "minutes"
const string DAYS = "days"
const string WEEKS = "weeks"
const string MONTHS = "months"
const string YEARS = "years"

// Singular forms
const string BAR = "bar"
const string SECOND = "second"
const string MINUTE = "minute"
const string DAY = "day"
const string WEEK = "week"
const string MONTH = "month"
const string YEAR = "year"

///////////////////////////////////////////////////
// TYPES
///////////////////////////////////////////////////

// @enum Time unit types for conversion functions
export enum Unit
    Bars
    Seconds
    Minutes
    Days

///////////////////////////////////////////////////
// @function Gets the number of milliseconds per bar.
export bar() =>
    var int msPerDay = 1000 * 60 * 60 * 24
    var int m = switch
        timeframe.isdaily => msPerDay
        timeframe.isweekly => msPerDay * 7
        timeframe.ismonthly => msPerDay * 30
        timeframe.isseconds => 1000
        timeframe.isminutes => 1000 * 60
        => na
    var value = m * timeframe.multiplier
    value
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Gets the start of the day for the provided time value.
// @param datetime The date/time to acquire the date from.
// @returns The number of milliseconds representing the date for the given value.
export date(int datetime = time) =>
    timestamp(year(datetime), month(datetime), dayofmonth(datetime))
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Gets milliseconds from the start of the day.
// @param datetime The date/time to acquire the time of day from.
// @returns The number of milliseconds representing time of day.
export timeOfDay(int datetime = time) =>
    datetime - date(datetime)
///////////////////////////////////////////////////

// Normalizes timespan and timeframe values.
adjustTimeframe(simple float timespan, simple string unit) =>
    var typeLower = str.lower(unit)
    var ts = switch typeLower
        BAR => BARS
        SECOND => SECONDS
        MINUTE => MINUTES
        DAY => DAYS
        WEEK => WEEKS
        MONTH => MONTHS
        YEAR => YEARS
        => typeLower

    var dayMultiple = switch ts
        WEEKS => 7
        MONTHS => 30
        YEARS => 365
        => 1

    var t = dayMultiple == 1 ? ts : DAYS
    var s = timespan * dayMultiple
    [s,t]
///

///////////////////////////////////////////////////
// @function Returns the number (float) bars that represents the timespan provided.
// @param timespan The number of units to convert to bar count.
// @param unit The type of units to measure. ('Bar', 'Bars', 'Minute', 'Minutes', 'Day' or 'Days')
// @param sessionMinutes Optional override for the number of minutes per session.  (Default: Regular = 390, Extended = 1440)
// @returns The number bars that represents the timespan provided.
export spanToLen(simple float timespan, simple string unit, simple int sessionMinutes = na) =>
    var sess_minutes = na(sessionMinutes)
      ? (syminfo.session == session.regular ? 390 : 1440)
      : sessionMinutes

    var float minutesPerBar = switch
        timeframe.isminutes => timeframe.multiplier
        timeframe.isseconds => timeframe.multiplier / 60
        timeframe.isdaily => sess_minutes
        timeframe.isweekly => sess_minutes * 7
        timeframe.ismonthly => sess_minutes * 30
        => na

    [s, t] = adjustTimeframe(timespan, unit)

    switch t
        BARS => s
        SECONDS => s / minutesPerBar
        MINUTES => s / minutesPerBar
        DAYS => timeframe.isintraday ?
          (sess_minutes * s / minutesPerBar) :
          timeframe.isdaily ? s :
          timeframe.isweekly ? s / 7 :
          timeframe.ismonthly ? s / 30 :
          na
        => na
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Returns the number (float) bars that represents the timespan provided.
// @param timespan The number of units to convert to bar count.
// @param unit The type of units to measure as a Unit enum ('Bars', 'Seconds', 'Minutes', 'Days').
// @param sessionMinutes Optional override for the number of minutes per session.  (Default: Regular = 390, Extended = 1440)
// @returns The number bars that represents the timespan provided.
export spanToLen(simple float timespan, simple Unit unit, simple int sessionMinutes = na) =>
    spanToLen(timespan, str.tostring(unit), sessionMinutes)
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Returns the number (int) bars that represents the timespan provided.
// @param timespan The number of units to convert to bar count.
// @param unit The type of units to measure. ('Bar', 'Minute' or 'Day')
// @returns The number bars that represents the timespan provided.
export spanToIntLen(simple float timespan, simple string unit) =>
    math.ceil(spanToLen(timespan, unit))
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Returns the number (int) bars that represents the timespan provided.
// @param timespan The number of units to convert to bar count.
// @param unit The type of units to measure as a Unit enum ('Bars', 'Seconds', 'Minutes', 'Days').
// @returns The number bars that represents the timespan provided.
export spanToIntLen(simple float timespan, simple Unit unit) =>
    spanToIntLen(timespan, str.tostring(unit))
///////////////////////////////////////////////////

plot(bar())

Overview

Functions retrieve milliseconds per bar based on timeframe, calculate the start of the day from a datetime, get time of day, and convert timespans between units like seconds, minutes, days to bars. It adjusts timeframes and supports common units like bars, seconds, minutes, days, weeks, months, years. These tools aid in precise time-based calculations for trading strategies.

Details

Published by

Electrified-Trading on GitHub

Code credit

Electrified, as written in the script's header

Type

Library, Pine Script v6

Draws

Library (no plots)

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

261 stars

AIActivationFunctionsBipolarSigmoid is a Pine Script library that provides mathematical implementations of the bipolar sigmoid activation function and its derivatives for machine learning algorithms. It calculates bipolar sigmoid values bounded between -1 and

Library v5 AI / machine learning
Updated 4 years ago · None stated GitHub repository of AIActivationFunctionsBipolarSigmoid

KernelFunctions

by artificial-intelligence-edge
75 stars

KernelFunctions is a Pine Script v5 library that exports kernel weight functions for Nadaraya-Watson style estimation. It calculates a Rational Quadratic kernel, a Gaussian kernel based on a radial basis function, and a periodic kernel that models repeating be

Library v5
Updated 2 days ago · MIT GitHub repository of KernelFunctions

Ta

by nersent
29 stars

This Pine Script v5 library exports thin wrappers around built-in technical analysis functions. It covers moving averages, momentum measures such as RSI and CCI, volatility tools including ATR and standard deviation, range extremes, cross detection, and runnin

Library v5
Updated 11 months ago · Custom licence GitHub repository of Ta

Bands

by heyphat
26 stars

This library exports a Band type and functions that build a simple-moving-average basis with upper and lower envelopes from standard deviation. It classifies a source as above, below, or inside those envelopes, measures band width, and scales an imported z-sco

Library v6 Volatility & bandsMoving averages
Updated 2 months ago · AGPL-3.0 GitHub repository of Bands

Mylib

by ferranbt
21 stars

This script serves as a minimal utility library written in Pine Script v6. It provides an exported helper function that calculates the sum of two numeric arguments. As a reusable code library, it produces no visual plots, charts, or trading signals, and it con

Library v6
Updated 7 weeks ago · MPL-2.0 GitHub repository of Mylib

HLevel

by stupenkov
14 stars

HLevel is a Pine Script v5 utility library designed to manage horizontal price levels for cryptocurrency charts. It defines custom types for pivots and levels, along with methods to initialize, add, track, and expire price levels based on pivot high and pivot

Library v5
Updated 3 years ago · None stated GitHub repository of HLevel

More libraries

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers