openhab-scripters / openhab-helper-libraries

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

days_between function in date.py #107

Closed besynnerlig closed 5 years ago

besynnerlig commented 5 years ago

The function days_between() in Core/automation/lib/python/core/date.py returns the "whole" number of days between to DateTimes.

def days_between(value_from, value_to):
    '''Returns number of whole days between value_from and value_to. 
    Accepts any date type used by this module'''
    return DAYS.between(to_java_zoneddatetime(value_from), to_java_zoneddatetime(value_to))

If I have a datetime object from yesterday at 9 AM and I compare it with a datetime today at 8 AM days_between will return 0 days. Can the function be modified so that it optionally only cares about dates. In that way I can use the function to check if a datetime was yesterday.

5iver commented 5 years ago

I see what you mean. In this function, 'days' means 24 hour intervals, not calendar days. Currently, it fits with the functionality of the other similar functions in the module. Adding the parameter calendar_days=False would help. I can add this after the repo rename, or someone else can pick it up before then. For now though, you could do...

from org.joda.time import DateTime
from core.date import to_java_zoneddatetime

today = to_java_zoneddatetime(DateTime.now()).toLocalDate()
yesterday = to_java_zoneddatetime(DateTime.now().minusHours(23)).toLocalDate()

if yesterday.plusDays(1).equals(today):
    log.warn("That was yesterday")
5iver commented 5 years ago

I couldn't put this down :smile:. Let me know if this works for you @besynnerlig!

besynnerlig commented 5 years ago

I couldn't put this down 😄. Let me know if this works for you @besynnerlig!

Thank you very much @openhab-5iver

You made my day! The modified function works very well here. 😄