Why is my time difference off by a second?

I have script for when a alarm is cleared to calculate how long the alarm was on. But when I test it out, the difference is sometimes off by a second.

def alarmCleared(tag, tagPath, alarmName, alarmEvent, alarmPath, missedEvents):

   # Get alarm details
	alarm = system.tag.read(tagPath).value
	active = alarmEvent.activeData.timestamp
	clear = alarmEvent.clearedData.timestamp

    # Convert Timestamp objects to java.util.Date if needed
	active_date = system.date.fromMillis(active)
	clear_date = system.date.fromMillis(clear)

    # Extract values
	value1 = exempt_default(tagPath)
	value2 = alarmName
	value3 = system.date.format(active_date, "MM/dd/yyyy")
	value4 = system.date.format(active_date, "hh:mm:ss a")
	value5 = system.date.format(clear_date, "hh:mm:ss a")

	# Calculate duration using system.date functions
	duration_seconds = system.date.secondsBetween(active_date, clear_date)

    # Round the duration to the nearest second
	rounded = round(duration_seconds)

    # Convert rounded duration to hours, minutes, and seconds
	hours = int(rounded // 3600)
	minutes = int((rounded % 3600) // 60)
	seconds = int(rounded % 60)
	
    # Format duration as HH:mm:ss
	value6 = "{:02}:{:02}:{:02}".format(hours, minutes, seconds)

    # Insert into database
	query = "INSERT INTO Alarm (Machine, Name, Date, TimeOn, TimeOff, Duration) VALUES (?,?,?,?,?,?)"
	args = [value1, value2, value3, value4, value5, value6]
	system.db.runPrepUpdate(query, args)
	
def exempt_default(tag_path):
	# Check if [default] is present in tag_path and remove it
	return tag_path.replace("[default]", "") if "[default]" in tag_path else tag_path

I'ds say it's rounding depending on the milliseconds. It is, still part of the date.

What happens of you use something like

duration_seconds = (clear - active) / 1000.0

or, if you're just looking to truncate the milliseconds:

duration_seconds = (clear - active) // 1000

Thank you, the duration_seconds = (clear - active) / 1000.0 fixed the issue.

1 Like