This article will delve into the str.format_time()
function, covering its syntax, usage, and practical examples.
Syntax
The str.format_time()
function converts a UNIX timestamp into a string formatted according to the specified format and timezone. Its syntax is as follows:
str.format_time(timeStamp, dateFormat, timeZone) → series string
Arguments
timeStamp
(series int
): The UNIX time, in milliseconds, to be formatted.dateFormat
(series string
): Specifies the date/time representation. It uses formatting tokens to denote how the date and time should be displayed. The default format is"yyyy-MM-dd'T'HH:mm:ssZ"
.timeZone
(series string
): Adjusts the returned value to a specified time zone, using either UTC/GMT notation or an IANA time zone database name. The default issyminfo.timezone
.
Example
To understand how the str.format_time()
function can be applied, consider the following example:
//@version=5 indicator("Custom Time Formatter") if timeframe.change("1D") customFormattedTime = str.format_time(time, "yyyy-MM-dd HH:mm", syminfo.timezone) label.new(bar_index, high, customFormattedTime, style=label.style_label_down)
This script creates an indicator named “Custom Time Formatter” that generates a label at the highest price of each day. The label displays the date and time formatted as “Year-Month-Day Hour:Minute”.
Detailed Walkthrough
- The
indicator
function defines a new indicator with the name “Custom Time Formatter”. timeframe.change("1D")
checks if there has been a change in the daily timeframe, ensuring the label is created once per day.str.format_time(time, "yyyy-MM-dd HH:mm", syminfo.timezone)
formats the current bar’s timestamp into a more readable date and time format, adjusted to the chart’s timezone.label.new(bar_index, high, customFormattedTime, style=label.style_label_down)
creates a new label at the highest price of the current bar, displaying the formatted timestamp.
Takeaways
- The
str.format_time()
function is essential for formatting time and date values in Pine Script. - It offers flexibility in how date and time are displayed through the use of formatting tokens.
- Adjusting the timezone allows for consistent time representation across different markets and geographical areas.
- Practical use cases include creating custom labels or annotations on charts that require precise date and time information.
Understanding and applying the str.format_time()
function can significantly enhance the readability and functionality of custom Pine Script indicators and strategies, making it a valuable tool for any financial analyst or trader using TradingView.