Jython datetime java issue with global variable

Running openhabian on Pi4
openHAB 3.4.0 Build #3029
jython rules

I’ve seen the thread regarding this issue and suggestions to not use datetime, but I wanted to add this here anyway since it seems so bizarre.

I use datetime in many modules in the exact same manner as below (well obviously there must be something different, but anyway) … as you can see by the code below, if I declare a global variable datetime becomes <type ‘java.sql.Timestamp’> … without the global it works fine. I saw recommendations to import core.date … but that made no difference (as the thread said as well)

The weird thing is that I can go back to other code I have and add a global and the problem does not occur. Short of not using datetime, has someone else got around this?

#import core.date

from core.rules import rule
from core.triggers import when
from datetime import datetime 

lastDoorClosed1 = None
lastDoorClosed2 = None

from org.slf4j import LoggerFactory
from configuration import LOG_PREFIX
log = LoggerFactory.getLogger("{}.rules testing".format(LOG_PREFIX))

@rule("Test Rule 1")
@when("Item TestButton changed to ON")
def rTestRule1(event):
#    global lastDoorClosed1

    lastDoorClosed1 = datetime.now()
    log.info("Type is correct: lastDoorClosed1=%s, type=%s" % (lastDoorClosed1,type(lastDoorClosed1)))

@rule("Test Rule 2")
@when("Item TestButton changed to ON")
def rTestRule2(event):
    global lastDoorClosed2

    lastDoorClosed2 = datetime.now()
    log.info("Type is NOT correct: lastDoorClosed2=%s, type=%s" % (lastDoorClosed2,type(lastDoorClosed2)))

2022-11-08 15:38:15.443 [INFO ] [jsr223.jython.rules testing         ] - Type is correct: lastDoorClosed1=2022-11-08 15:38:15.438000, type=<class 'datetime.datetime'>
2022-11-08 15:38:15.447 [INFO ] [jsr223.jython.rules testing         ] - Type is NOT correct: lastDoorClosed2=2022-11-08 07:38:15.443, type=<type 'java.sql.Timestamp'>

All I remember is that it is a bug upstream in the Jython code itself. There really isn’t anything you can do about it except to not use global datetimes. java.time.ZonedDateTime can do everything you need with the added bonus that you need to use it any time you interact with openHAB anyway so you may as well be consistent.

If you really want to stick to a pure Java Python experience, HABApp should be on your radar.

1 Like

Thanks Rich. Yes been switching over to java.time.ZonedDateTime just doing it gradually (wife complains when I break things lol) … it was just weird that in some cases the global worked (it was actually a global list that works fine in other rules.)

Yes planning for that too. Did you mean Python though?

Yes, brain fart. I meant Python.

1 Like