openhab-scripters / openhab-helper-libraries

Scripts and modules for use with openHAB
Eclipse Public License 1.0
88 stars 69 forks source link

[core.date] create function to get an offset-aware datetime #236

Closed rkoshak closed 3 years ago

rkoshak commented 4 years ago

Is your feature request related to a problem? Please describe. I'm working on a countdown timer class which needs to do comparisons and math with datetime. Python has excellent support for doing this so I want to use Python classes (datetime, timeoffset, etc.). When I use datetime.now() or datetime.today() I get an offset-naive datetime. However, when I call to_python_datetime with a Joda DateTime object, I get an offset-aware datetime.

Unfortunately you cannot perform comparison or math operations with two different types of datetimes which severely breaks the utility of to_python_datetime.

Describe the solution you'd like Rather than hobbling the datetime obtained by to_python_datetime by removing TX info, I think it would be better to provide a function that returns an offset-aware Python datetime for now(). Then we do not force the users to code their own tzinfo class which is a pain.

Describe alternatives you've considered Avoid the use of Joda DateTime. I'm not sure if passing a Java Date to the function will generate an offset-aware datetime or not.

Additional context Add any other context or screenshots about the feature request here.

5iver commented 3 years ago

When Jython assigns a datetime.datetime or datetime.date object to a variable, it is converted to a java.sql.Timestamp object through its __tojava__ method. Using the helper libraries, core.date.to_python_datetime returns a datetime.datetime by removing this method with... https://github.com/openhab-scripters/openhab-helper-libraries/blob/master/Core/automation/lib/python/core/date.py#L38-45. The only way to avoid getting a java.sql.Timestamp is to do the same. This is a good example of why it is best to use Java rather than native Python objects.