Exemple #1
0
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))))
Exemple #2
0
    def test_datetime_with_time_zone(self):
        oldDefaultTimeZone = TimeZone.getDefault()
        try:
            TimeZone.setDefault(TimeZone.getTimeZone("GMT+4"))
            c = tWithDateTimeZCursor(self.context)

            zoneId = ZoneId.of("GMT+2")
            #This is the datetime we will insert
            localDateTime = LocalDateTime.of(2017, Month.DECEMBER, 31, 22, 0,
                                             0)
            zonedDateTime = ZonedDateTime.of(localDateTime, zoneId)
            #This is the datetime we expect the database to receive
            utcDateTime = LocalDateTime.of(2018, Month.JANUARY, 1, 0, 0, 0)

            c.eventDate = zonedDateTime
            c.insert()
            c.clear()

            c.first()

            zoneIdAfterSelect = ZoneId.of("GMT+4")
            self.assertEquals(utcDateTime, c.eventDate.toLocalDateTime())
            self.assertEquals(zoneIdAfterSelect, c.eventDate.getZone())

        finally:
            TimeZone.setDefault(oldDefaultTimeZone)
Exemple #3
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)))
Exemple #4
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
Exemple #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)))
Exemple #6
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]
Exemple #7
0
    def onConfigure(self):
        self.withLabel("Type date-time arg action")
        self.withArgs([
            DateTimeType("arg").withLabel("Date-time non nullable").withDefaultValue(LocalDateTime.of(2020, 1, 1, 12, 0)),
            DateTimeType("argNullable").withLabel("Date-time nullable").withNullable(),
            DateTimeType("argDefault").withLabel("Date-time with default").withDefaultValue(LocalDateTime.of(2020, 1, 1, 12, 0)),
            DateTimeType("argReadOnlyNullable").withLabel("Date-time read only nullable").withReadOnly().withNullable()
                .withDefaultValue(LocalDateTime.of(2020, 1, 1, 12, 0)),
            DateTimeType("argReadOnlyNonNullable").withLabel("Date-time read only non nullable").withReadOnly()
                .withDefaultValue(LocalDateTime.of(2020, 1, 1, 12, 0)),

            DateTimeType("argDate").withDate().withLabel("Date non nullable").withDefaultValue(LocalDate.of(2020, 1, 1)),
            DateTimeType("argDateNullable").withDate().withLabel("Date nullable").withNullable(),
            DateTimeType("argDateDefault").withDate().withLabel("Date with default").withDefaultValue(LocalDate.of(2020, 1, 1)),
            DateTimeType("argDateReadOnlyNullable").withDate().withLabel("Date read only nullable").withReadOnly().withNullable()
                .withDefaultValue(LocalDate.of(2020, 1, 1)),
            DateTimeType("argDateReadOnlyNonNullable").withDate().withLabel("Date read only non nullable").withReadOnly()
                .withDefaultValue(LocalDate.of(2020, 1, 1)),

            DateTimeType("argTime").withTime().withFormat("HH:mm").withLabel("Time non nullable").withDefaultValue(LocalTime.of(12, 0)),
            DateTimeType("argTimeNullable").withTime().withFormat("HH:mm").withLabel("Time nullable").withNullable(),
            DateTimeType("argTimeDefault").withTime().withFormat("HH:mm").withLabel("Time with default").withDefaultValue(LocalTime.of(12, 0)),
            DateTimeType("argTimeReadOnlyNullable").withTime().withFormat("HH:mm").withLabel("Time read only nullable").withReadOnly().withNullable()
                .withDefaultValue(LocalTime.of(12, 0)),
            DateTimeType("argTimeReadOnlyNonNullable").withTime().withFormat("HH:mm").withLabel("Time read only non nullable").withReadOnly()
                .withDefaultValue(LocalTime.of(12, 0)),

            DateTimeType("argDateTimeZoneReadOnlyNullable").withDateTimeZone().withLabel("Date-time-zone read only nullable").withReadOnly().withNullable()
                .withDefaultValue(ZonedDateTime.of(LocalDateTime.of(2020, 1, 1, 12, 0), ZoneId.of("America/Detroit"))),
            DateTimeType("argDateTimeZoneReadOnlyNonNullable").withDateTimeZone().withLabel("Date-time-zone read only non nullable").withReadOnly()
                .withDefaultValue(ZonedDateTime.of(LocalDateTime.of(2020, 1, 1, 12, 0), ZoneId.of("America/Detroit"))),

            DateTimeType("argInstantReadOnlyNullable").withInstant().withLabel("Instant read only nullable").withReadOnly().withNullable()
                .withDefaultValue(Instant.now()),
            DateTimeType("argInstantReadOnlyNonNullable").withInstant().withLabel("Instant read only non nullable").withReadOnly()
                .withDefaultValue(Instant.now()),

            # DATE_TIME_ZONE and INSTANT editing is not supported yet.
        ]).withResult(StringType())
Exemple #8
0
 def onCall(self, type):
     if type == "nonNullable":
         return DynamicValue(LocalDateTime.of(2020, 1, 1, 12, 0), DateTimeType().withLabel("Date-time non nullable"))
     elif type == "nullable":
         return DynamicValue(None, DateTimeType().withLabel("Date-time nullable").withNullable())
     elif type == "readOnlyNullable":
         return DynamicValue(None, DateTimeType().withLabel("Date-time read only nullable").withReadOnly().withNullable())
     elif type == "readOnlyNonNullable":
         return DynamicValue(LocalDateTime.of(2020, 1, 1, 12, 0), DateTimeType().withLabel("Date-time read only non nullable").withReadOnly())
     if type == "dateNonNullable":
         return DynamicValue(LocalDate.of(2020, 1, 1), DateTimeType().withDate().withLabel("Date non nullable"))
     elif type == "dateNullable":
         return DynamicValue(None, DateTimeType().withDate().withLabel("Date nullable").withNullable())
     elif type == "dateReadOnlyNullable":
         return DynamicValue(None, DateTimeType().withDate().withLabel("Date read only nullable").withReadOnly().withNullable())
     elif type == "dateReadOnlyNonNullable":
         return DynamicValue(LocalDate.of(2020, 1, 1), DateTimeType().withDate().withLabel("Date-time read only non nullable").withReadOnly())
     if type == "timeNonNullable":
         return DynamicValue(LocalTime.of(12, 0), DateTimeType().withTime().withFormat("HH:mm").withLabel("Time non nullable"))
     elif type == "timeNullable":
         return DynamicValue(None, DateTimeType().withTime().withFormat("HH:mm").withLabel("Time nullable").withNullable())
     elif type == "timeReadOnlyNullable":
         return DynamicValue(None, DateTimeType().withTime().withFormat("HH:mm").withLabel("Time read only nullable").withReadOnly().withNullable())
     elif type == "timeReadOnlyNonNullable":
         return DynamicValue(LocalTime.of(12, 0), DateTimeType().withTime().withFormat("HH:mm").withLabel("Time read only non nullable").withReadOnly())
     if type == "dateTimeZoneReadOnlyNullable":
         return DynamicValue(None,
                             DateTimeType().withDateTimeZone().withLabel("Date-time-zone read only nullable").withReadOnly().withNullable())
     elif type == "dateTimeZoneReadOnlyNonNullable":
         return DynamicValue(ZonedDateTime.of(LocalDateTime.of(2020, 1, 1, 12, 0), ZoneId.of("America/Detroit")),
                             DateTimeType().withDateTimeZone().withLabel("Date-time-zone read only non nullable").withReadOnly())
     if type == "instantReadOnlyNullable":
         return DynamicValue(None, DateTimeType().withInstant().withLabel("Instant read only nullable").withReadOnly().withNullable())
     elif type == "instantReadOnlyNonNullable":
         return DynamicValue(Instant.now(), DateTimeType().withInstant().withLabel("Instant read only non nullable").withReadOnly())
     else:
         return None
Exemple #9
0
from mil.army.usace.hec.vortex.math import Normalizer
from mil.army.usace.hec.vortex.io import DataReader

from java.time import ZonedDateTime
from java.time import LocalDateTime
from java.time import ZoneId
from java.time import Duration

source = "C:/Temp/qpe.dss"
normals = "C:/Temp/prism.dss"

sourceGrids = DataReader.getVariables(source)
normalGrids = DataReader.getVariables(normals)

start = ZonedDateTime.of(LocalDateTime.of(2017, 1, 1, 0, 0), ZoneId.of("UTC"))
end = ZonedDateTime.of(LocalDateTime.of(2017, 1, 3, 0, 0), ZoneId.of("UTC"))
interval = Duration.ofDays(1)

destination = 'C:/Temp/normalized.dss'

options = {'partF': 'my normalized grids'}

normalizer = Normalizer.builder() \
    .startTime(start) \
    .endTime(end) \
    .interval(interval) \
    .pathToSource(source) \
    .sourceVariables(sourceGrids) \
    .pathToNormals(normals) \
    .normalsVariables(normalGrids) \
    .destination(destination) \
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
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
Exemple #12
0
 def __init__(self, zid=ZoneId.of("UTC")):
     self.zid = zid
     self.fb = self.format_builder()