How to count minutes into shift?

How do I count minutes/hours into current shift? What is wrong with this script that runs in tag history binding ‘Most recent’ expression editor.

def getMinutesIntoShift():
now = system.date.now()

today730am = system.date.setTime(now, 7, 30, 0)
today730pm = system.date.setTime(now, 19, 30, 0)

if today730am <= now < today730pm:
    shiftStart = today730am
else:
    if now < today730am:
        shiftStart = system.date.addDays(today730pm, -1)
    else:
        shiftStart = today730pm

minutesIntoShift = system.date.minutesBetween(shiftStart, now)
return int(minutesIntoShift)

You've written a python function definition in something that is expecting an expression.

I would recommend converting that into a proper expression and placing that expression onto a custom view property. Call it something along the lines of shiftStartTs or similar. Then, bind the value for most Recent in the history binding to that custom property.

You might run into issues with multiple calls to now in the same expression, so I would recommend creating another custom property called currentTs or similar, and referencing that in your main expression binding.

1 Like

Try this expression:

floor(									// get integer value of minutes
	(now(10000) - 7.5 * 3600 * 1000) 	// now - 7.5 hours
	% (12 * 3600 * 1000)        		// modulo 12 hours
	/ 60000								// divided by 60 s.
)

Notes:

  • now(10000) causes it to update the minutes every 10 s (if there is a change). Make it smaller if required.
  • Since they're 12 hour shifts, you only need to subtract the shift start offset and get the 12 hour modulus which will get the number of milliseconds into the shift.
  • Divide that by the number of ms in a minute (60,000) and you've got your minutes into shift.

You can think of expressions being like Excel's functions (which you would write into a cell formula) and scripts being like Excel Developer VBA code.
Expressions take 0 or more inputs, perform an operation and output a result. You can't write a program in Expression Language.

3 Likes