Groovy not converting seconds to hours properly - groovy

I have an integer that is:
19045800
I tried different code:
def c = Calendar.instance
c.clear()
c.set(Calendar.SECOND, 19045800)
echo c.format('HH:mm:ss').toString()
String timestamp = new GregorianCalendar( 0, 0, 0, 0, 0, 19045800, 0 ).time.format( 'HH:mm:ss' )
echo timestamp
Both return 10:30:00
19045800 seconds is supposed to be over 5000 hours. What am I doing wrong?

I'm not sure what you are looking for. But if your requirement is to calculate the number of hours, minutes, and the remainder of seconds for given seconds following code will work.
def timeInSeconds = 19045800
int hours = timeInSeconds/3600
int minutes = (timeInSeconds%3600)/60
int seconds = ((timeInSeconds%3600)%60)
println("Hours: " + hours)
println("Minutes: " + minutes)
println("Seconds: " + seconds)

You're attempting to use a Calendar, but what you're actually discussing is what Java calls a Duration – a length of time in a particular measurement unit.
import java.time.*
def dur = Duration.ofSeconds(19045800)
def hours = dur.toHours()
def minutes = dur.minusHours(hours).toMinutes()
def seconds = dur.minusHours(hours).minusMinutes(minutes).toSeconds()
println "hours = ${hours}"
println "minutes = ${minutes}"
println "seconds = ${seconds}"
prints:
hours = 5290
minutes = 30
seconds = 0

Related

How to delay orders in pine script by numbers of minutes in 1hr timeframe?

I'm trying to delay entry orders by minutes.
ex: At 12:00 pm the macd line crossover signal line, but I wanna start entry.order at 12:02 pm.
So I tried the following code
//#version=4
strategy("delay2",calc_on_every_tick=true)
i_qtyTimeUnits = input(2, "Quantity", minval = 0)
int _timeFrom_ = na
_timeFrom_ := i_qtyTimeUnits*60*1000
// Entry conditions.
fastLength = input(12)
slowlength = input(26)
signalLength = input(9)
MACD = sma(close, fastLength) - sma(close, slowlength)
signal = sma(MACD, signalLength)
delta = MACD - signal
bool goLong = delta>0
bool goShort = delta<0
float entrytime = na
float delaytime = na
entrytime := if goLong
nz(entrytime[1], time)
delaytime := if entrytime>0
nz(delaytime[1], entrytime+_timeFrom_)
delayElapsed = time>=delaytime
plot(entrytime)
plot(delaytime)
plot(time)
if goLong and delayElapsed
strategy.entry("Long", strategy.long, comment="Long")
strategy.close('short', when = goShort)
I've plotted and checked that delayElapsed is true, but it just doesn't work,please help.
I made a script that buys 2 minutes after a red candle has appeared. The buy is marked with an X.
There is a variable in pine script that is called time. The variable keeps track at the time where every candle is displayed. time is the number of milliseconds since 1 Jan 1970. For example, the current time when I'm writing this is 1625334502399.
To determine the time when you should buy, you can add the number of milliseconds you want to the time and store it in a variable.
entrytime := time + 2 * 60 * 1000
So 2 minutes is equal to 2 * 60 * 1000 milliseconds. There are 1000 milliseconds on a second and 60 seconds on a minute.
You should store this value in a var variable because that value doesn't get erased after every bar.
var float entrytime = na
You can change to any timeframe and it will still buy 2 min after.
Here is the full code:
// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
// © CanYouCatchMe
//#version=4
study("buying after 2 min", overlay=true)
delay_minutes = input(defval = 2, title = "Delay minutes")
var float entrytime = na //is used to store the time when it should buy
if (open > close and na(entrytime)) //Red candle and there is no current "entrytime"
entrytime := time + delay_minutes * 60 * 1000 //"time" is the time in milliseconds where to candle appered. There is 1000 milliseconds on a second. And 60 seconds on a minute.
buy_condition = false
if (time >= entrytime) //Buys if the current time is greater or the same as the stored time.
entrytime := na //Sets entrytime to na so it stops buying.
buy_condition:=true
plotshape(buy_condition, style=shape.xcross, color=color.green, size=size.small) //Plotting an green "X" where it should buy
//Displaying the values "Data Window" on the right for Debugging.
plotchar(time, "time", "", location = location.top)
plotchar(entrytime, "entrytime", "", location = location.top)

Python: Unresolved Reference (variableName) when trying to refer to and use variables I declared at the top of the script, within a function

I declare these variables at the start of my python script:
hours = 0
mins = 0
secs = 0
Then I create a function, and want to make use of those variables within my function:
def calc_running_total():
hours = hours + int(running_total[0:2])
mins = mins + int(running_total[3:5])
if mins == 60 or mins > 60:
hours += 1
mins = mins - 60
secs = secs + int(running_total[6:8])
if secs == 60 or secs > 60:
mins += 1
secs = secs - 60
But it underlines hours, mins and secs after the assignment operator (=) in red, and says "Unresolved reference: Hours" and same for mins and secs.
How do I make use of variables declared at the top of my script within functions?
Thanks.
EDIT: I've been told to put "global hours" within the function definition.
But I don't have to do that for another function I've just defined, with variable "activity_type":
def add_to_correct_list():
if activity_type.casefold() == "work":
if day_and_date:
work_list.append((day_and_date))
print(f"\n{day_and_date} added to work_list")
work_list.append(activity_item_name + ": " + running_total)
print("\nItem and time tracking added to Work_List!")
Why don't I need to do that in this function?
# these are considered 'global vars'
hours = 0
mins = 0
secs = 0
def calc_running_total():
global hours # now the method will reference the global vars
global mins
global secs
hours = hours + int(running_total[0:2])
mins = mins + int(running_total[3:5])
if mins == 60 or mins > 60:
hours += 1
mins = mins - 60
secs = secs + int(running_total[6:8])
if secs == 60 or secs > 60:
mins += 1
secs = secs - 60
Other examples as requested:
hours = 1
def implicit_global():
print(hours) # 1
hours = 1
def point_to_global():
global hours
print(hours) # 1
print(hours+ 1) # 2
print(hours) # 2
hours = 1
def implicit_global_to_local():
local_hours = hours # copies the global var and sets as a local var
print(local_hours) # 1
print(local_hours + 1) # 2
print(hours) # 1

How to convert 24 hour format to 12 hour format in groovy [duplicate]

This question already has answers here:
How to convert 24 hr format time in to 12 hr Format?
(16 answers)
Closed 3 years ago.
I'm new to groovy and i want to convert 24 hour format to 12 hour format. What is the code to be used for it? Is there any built-in methods?
I just want groovy code not java one
Kevin's answer is correct, and should get the tick... I only post this as it's slightly shorter
import java.time.*
import static java.time.format.DateTimeFormatter.ofPattern
String time = '13:23:45'
String result = LocalTime.parse(time).format(ofPattern('h:mm:ss a'))
println result
I thought this question is somewhat similar to the How to convert 24 hr format time in to 12 hr Format?. It just that Java and Groovy share a lot of similarities. To point that out, I took Cloud's answer from the mentioned question and converted that to Groovy.
import java.time.LocalTime
import java.time.format.DateTimeFormatter
final String time = "21:49"
String result = LocalTime.parse(time, DateTimeFormatter.ofPattern("HH:mm")).format(DateTimeFormatter.ofPattern("hh:mm a"));
println(result)
If you want to build your own time function you can try to customize the code below.
final String time = "21:49"
final String _24to12( final String input ){
if ( input.indexOf(":") == -1 )
throw ("")
final String []temp = input.split(":")
if ( temp.size() != 2 )
throw ("") // Add your throw code
// This does not support time string with seconds
int h = temp[0] as int // if h or m is not a number then exception
int m = temp[1] as int // java.lang.NumberFormatException will be raised
// that can be cached or just terminate the program
String dn
if ( h < 0 || h > 23 )
throw("") // add your own throw code
// hour can't be less than 0 or larger than 24
if ( m < 0 || m > 59 )
throw("") // add your own throw code
// minutes can't be less than 0 or larger than 60
if ( h == 0 ){
h = 12
dn = "AM"
} else if ( h == 12 ) {
dn = "PM"
} else if ( h > 12 ) {
h = h - 12
dn = "PM"
} else {
dn = "AM"
}
return h.toString() + ":" + m.toString() + " " + dn.toString()
}
println(_24to12(time))

What is the impact of a function on execution speed?

Fairly new to python and working on an application where speed is critical - essentially in a race to book reservations online as close to 7AM as possible. Was trying to understand the impact on execution speed that a function call has, so i developed a very simple test: count to 1,000,000 and time start and end using both in line and a called function. However, the result i get says that the function takes about 56% of the time that the inline code takes. I must be really be missing something. Can anyone explain this please.
Code:
import time
def timeit():
temp = 0
while temp < 10000000:
temp += 1
return
time1 = time.time()
temp = 0
while temp < 10000000:
temp += 1
time2 = time.time()
timeit()
time3 = time.time()
temp = 0
while temp < 10000000:
temp += 1
time4 = time.time()
timeit()
time5 = time.time()
print("direct took " + "{:.16f}".format(time2 - time1) + " seconds")
print("indirect took " + "{:.16f}".format(time3 - time2) + " seconds")
print("2nd direct took " + "{:.16f}".format(time4 - time3) + " seconds")
print("2nd indirect took " + "{:.16f}".format(time5 - time4) + " seconds")
results:
direct took 1.6094279289245605 seconds
indirect took 0.9220039844512939 seconds
2nd direct took 1.5781939029693604 seconds
2nd indirect took 0.9375154972076416 seconds
I apologize for missing something silly that i must have done?

Retrieve decimals only from a variable

I'm making a distance/time used calculator where i'm trying to separate whole hours and minutes.
Code:
if (hours >= 1)
{
minutes = Number((hours-int.(hours))*60);
timeTxt.text = String(int.(hours)+" hours & "+(minutes)+" minutes");
}
else
{
timeTxt.text = String((hours*60).toFixed(0)+" minutes");
}
the "else" one is working and prints minutes only. But I can't get the first if statement to work. Trying to print "x hours & x minutes".
Getting this message in output:
TypeError: Error #1123: Filter operator not supported on type class int.
at Rutekalkulator2_fla::MainTimeline/calculate()
Couldn't you do something like:
(pseudocode)
double tmp = math.floor(yournumber);
yournumber = yournumber - tmp;
And that'll make your number be just the decimal part.
Besides that, I'm not really sure what your question is.
Convert everything to minutes then try the following:
timeTxt.text = String( totMinutes / 60 + ":" + totMinutes % 60);
// output 06:36
timeTxt.text = String( totMinutes / 60 + " hours and " + totMinutes % 60 + " minutes");
// output 6 hours and 36 minutes
I'm not fluent in Actionscript but if the modulo works the same as it does in other languages this should work for you.

Resources