コード例 #1
0
ファイル: date.py プロジェクト: chrispab/AutoHome
def to_java_zoneddatetime(value):
    """
    Converts any of the supported date types to ``java.time.ZonedDateTime``. If
    ``value`` does not have timezone information, the system default will be
    used.

    Examples:
        .. code-block::

            java_time = to_java_zoneddatetime(items["date_item"])

    Args:
        value: the value to convert

    Returns:
        java.time.ZonedDateTime: the converted value

    Raises:
        TypeError: if the type of ``value`` is not supported by this module
    """
    if isinstance(value, ZonedDateTime):
        return value
    timezone_id = ZoneId.systemDefault()
    # java.time.LocalDateTime
    if isinstance(value, LocalDateTime):
        return value.atZone(timezone_id)
    # python datetime
    if isinstance(value, datetime.datetime):
        if value.tzinfo is not None:
            timezone_id = ZoneId.ofOffset(
                "GMT",
                ZoneOffset.ofTotalSeconds(
                    int(value.utcoffset().total_seconds())))
        return ZonedDateTime.of(value.year, value.month, value.day, value.hour,
                                value.minute, value.second,
                                value.microsecond * 1000, timezone_id)
    # java.util.Calendar
    if isinstance(value, Calendar):
        return ZonedDateTime.ofInstant(value.toInstant(),
                                       ZoneId.of(value.getTimeZone().getID()))
    # java.util.Date
    if isinstance(value, Date):
        return ZonedDateTime.ofInstant(
            value.toInstant(),
            ZoneId.ofOffset(
                "GMT", ZoneOffset.ofHours(0 - value.getTimezoneOffset() / 60)))
    # Joda DateTime
    if JodaDateTime and isinstance(value, JodaDateTime):
        return value.toGregorianCalendar().toZonedDateTime()
    # openHAB DateTimeType
    if DateTimeType and isinstance(value, DateTimeType):
        return to_java_zoneddatetime(value.getZonedDateTime())
    # Eclipse Smarthome DateTimeType
    if EclipseDateTimeType and isinstance(value, EclipseDateTimeType):
        return to_java_zoneddatetime(value.calendar)
    # Legacy (OH1.x compat) DateTimeType
    if LegacyDateTimeType and isinstance(value, LegacyDateTimeType):
        return to_java_zoneddatetime(value.calendar)

    raise TypeError("Unknown type: {}".format(str(type(value))))
コード例 #2
0
def getItemLastUpdate(itemOrName):
    item = _getItem(itemOrName)
    lastUpdate = PersistenceExtensions.lastUpdate(item)
    if lastUpdate is None:
        return ZonedDateTime.ofInstant(Instant.ofEpochMilli(0),
                                       ZoneId.systemDefault())
        #raise NotInitialisedException("Item lastUpdate for '" + item.getName() + "' not found")
    return lastUpdate
コード例 #3
0
def getStableMinMaxItemState(now, itemName, checkTimeRange):

    currentEndTime = now
    currentEndTimeMillis = currentEndTime.toInstant().toEpochMilli()
    minTimeMillis = currentEndTimeMillis - (checkTimeRange * 60 * 1000)

    minValue = None
    maxValue = None

    value = 0.0
    duration = 0

    # get and cache "real" item to speedup getHistoricItemEntry. Otherwise "getHistoricItemEntry" will lookup the item by its name every time
    item = getItem(itemName)

    entry = getHistoricItemEntry(item, now)

    while True:
        currentStartMillis = entry.getTimestamp().toInstant().toEpochMilli()

        if currentStartMillis < minTimeMillis:
            currentStartMillis = minTimeMillis

        _duration = currentEndTimeMillis - currentStartMillis
        _value = entry.getState().doubleValue()

        if minValue == None or minValue > _value:
            minValue = _value

        if maxValue == None or maxValue < _value:
            maxValue = _value

        duration = duration + _duration
        value = value + (_value * _duration)

        currentEndTimeMillis = currentStartMillis - 1

        if currentEndTimeMillis < minTimeMillis:
            break

        currentEndTime = ZonedDateTime.ofInstant(
            Instant.ofEpochMilli(currentEndTimeMillis), ZoneId.systemDefault())

        entry = getHistoricItemEntry(item, currentEndTime)

    value = (value / duration)

    return [value, minValue, maxValue]
コード例 #4
0
def to_java_zoneddatetime(value):
    """Converts any known DateTime type to a ``java.time.ZonedDateTime`` type.

    Args:
        value: any known DateTime value.
    
    Returns:
        | A ``java.time.ZonedDateTime`` representing ``value``.
        | If ``value`` does not have timezone information, the system default
          will be used.
    
    Raises:
        TypeError: type of ``value`` is not recognized by this package.
    """
    timezone_id = ZoneId.systemDefault()
    if isinstance(value, ZonedDateTime):
        return value
    # java.time.LocalDateTime
    if isinstance(value, LocalDateTime):
        return value.atZone(timezone_id)
    # python datetime
    if isinstance(value, datetime.datetime):
        if value.tzinfo is not None:
            timezone_id = ZoneId.ofOffset(
                "GMT",
                ZoneOffset.ofTotalSeconds(value.utcoffset().total_seconds()))
        return ZonedDateTime.of(value.year, value.month, value.day, value.hour,
                                value.minute, value.second,
                                value.microsecond * 1000, timezone_id)
    # java.util.Calendar
    if isinstance(value, Calendar):
        return ZonedDateTime.ofInstant(value.toInstant(),
                                       ZoneId.of(value.getTimeZone().getID()))
    # java.util.Date
    if isinstance(value, Date):
        return ZonedDateTime.ofInstant(
            value.toInstant(),
            ZoneId.ofOffset(
                "GMT",
                ZoneOffset.ofTotalSeconds(value.getTimezoneOffset() * 60)))
    # Joda DateTime
    if isinstance(value, DateTime):
        return value.toGregorianCalendar().toZonedDateTime()
    # OH DateTimeType or ESH DateTimeType
    if isinstance(value, (LegacyDateTimeType, DateTimeType)):
        return to_java_zoneddatetime(value.calendar)

    raise TypeError("Unknown type: " + str(type(value)))
コード例 #5
0
def to_java_zoneddatetime(value):
    '''Returns java.time.ZonedDateTime (with system timezone, if none specified). 
    Accepts any date type used by this module.'''
    timezone_id = ZoneId.systemDefault()
    if isinstance(value, ZonedDateTime):
        return value
    # java.time.LocalDateTime
    if isinstance(value, LocalDateTime):
        return value.atZone(timezone_id)
    # python datetime
    if isinstance(value, datetime.datetime):
        if value.tzinfo is not None:
            timezone_id = ZoneId.ofOffset(
                "GMT",
                ZoneOffset.ofTotalSeconds(value.utcoffset().total_seconds()))
        return ZonedDateTime.of(value.year, value.month, value.day, value.hour,
                                value.minute, value.second,
                                value.microsecond * 1000, timezone_id)
    # java.util.Calendar
    if isinstance(value, Calendar):
        return ZonedDateTime.ofInstant(value.toInstant(),
                                       ZoneId.of(value.getTimeZone().getID()))
    # java.util.Date
    if isinstance(value, Date):
        return ZonedDateTime.ofInstant(
            value.toInstant(),
            ZoneId.ofOffset(
                "GMT",
                ZoneOffset.ofTotalSeconds(value.getTimezoneOffset() * 60)))
    # Joda DateTime
    if isinstance(value, DateTime):
        return value.toGregorianCalendar().toZonedDateTime()
    # OH DateTimeType or ESH DateTimeType
    if isinstance(value, (LegacyDateTimeType, DateTimeType)):
        return to_java_zoneddatetime(value.calendar)

    raise Exception("Invalid conversion: " + str(type(value)))
コード例 #6
0
today = LocalDate.now()
if timePeriod == "Last 30 days":
    fromDate = today.minusDays(30)
    toDate = today
elif timePeriod == "Last 3 months":
    fromDate = today.minusMonths(3)
    toDate = today
elif timePeriod == "Last 6 months":
    fromDate = today.minusMonths(6)
    toDate = today
elif timePeriod == "Last year":
    fromDate = today.minusYears(1)
    toDate = today
else:
    fromDate = fromDate.toInstant().atZone(
        ZoneId.systemDefault()).toLocalDate()
    toDate = toDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()

# Use time windows to get deployments.  This is the first window
fromRegion, toRegion = increment_time_windows(fromDate, dateAggregation)

dates = []
deployments = []
change_failure = []
period_covered = False

while fromRegion < toDate:
    deployment_count = 0
    rollback_count = 0
    results_remain = True
    page = 1
コード例 #7
0
reload(community.time_utils)
from community.time_utils import to_today, to_datetime
from core.date import days_between, seconds_between, to_python_datetime, to_joda_datetime, to_java_zoneddatetime
from core.log import logging, LOG_PREFIX
from org.joda.time import DateTime
from java.time import ZonedDateTime, ZoneId
from java.time.temporal import ChronoUnit

log = logging.getLogger("{}.TEST.time_utils".format(LOG_PREFIX))

#To_today tests

today_time = to_today(time(23, 00, 00, 00))
today_datetime = to_today(datetime(2019, 10, 8, 23, 00, 00, 00))
today_ZonedDateTime = to_today(
    ZonedDateTime.of(2019, 11, 8, 23, 00, 00, 00, ZoneId.systemDefault()))

try:
    log.info(
        "start test to_today with different input and output Joda datetime")
    #Check date was changed
    assert days_between(
        ZonedDateTime.now(),
        today_time) == 0, "time object failed to change date for today"
    assert days_between(
        ZonedDateTime.now(),
        today_datetime) == 0, "datetime object failed to change date for today"
    assert days_between(
        ZonedDateTime.now(), today_ZonedDateTime
    ) == 0, "ZonedDateTime object failed to change date for today"
    #Check time wasn't changed