def post(self, resource_id = None):
        data = request.get_json()
        verify_request_contains_mandatory_fields(data, self.mandatory_fields)

        # Resource id might also be part of the incoming json.
        resource_uri = None
        if not resource_id:
            resource_uri = data["resource_uri"]

        resource = self.get_resource_with_id_or_uri(resource_id, resource_uri)

        start_date, end_date = self.parse_date_range_from_dict(data)

        start_time = parse_time(data["start_time"])
        end_time = parse_time(data["end_time"])
        week_day = data["week_day"]
        if data["note"]:
            note = data["note"]
            if not (len(note) <= 50):
                abort(400, __error__=[u'Maks lengde for merknad er 50 tegn'])
        else:
            note= ""


        self.validate_start_and_end_times(start_date, end_date, start_time, end_time)

        # Check that the time has correct minute interval, only 30-minute intervals allowed
        invalid_minutes = filter(lambda my_time: my_time.minute not in [0, 30], [start_time, end_time])
        if invalid_minutes:
            abort(400,
                  __error__=[u'Tidene må angis i hele halvtimer']
            )

        weekly_blocked_time = WeeklyBlockedTime(resource, week_day,
            start_date, end_date, start_time, end_time, note)
        ensure(POST, weekly_blocked_time)

        if self.is_conflict_slot_time(resource, start_date, end_date, week_day, start_time, end_time) or \
                self.is_conflict_rammetid(resource, start_date, end_date, week_day, start_time, end_time):
            abort(
                400,
                __error__=[u'Tiden er ikke tilgjengelig for blokkering']
            )       
        if self.is_conflict_blocked_time(resource, start_date, end_date, week_day, start_time, end_time):
            abort(
                400,
                __error__=[u'Tiden er allerede blokkert']
            )                 

        current_app.db_session.add(weekly_blocked_time)
        current_app.db_session.commit()
        current_app.db_session.refresh(weekly_blocked_time)

        return marshal(weekly_blocked_time, self.fields), 201
    def test_001_trmm_3b42_daily_v6_v7(self):
        # Testing Phase
        # --------------------------------------------------------------
        data = [
            ('d/001/scrubbed.TRMM_3B42_daily_precipitation_V6.20050101.nc',
             'd/001/scrubbed.TRMM_3B42_daily_precipitation_V7.20050101.nc')
        ]
            
        with open(self.opt_f, 'w') as fh:
            for x_file, y_file in data:
                fh.write(os.path.join(cur_dir, x_file))
                fh.write(' ')
                fh.write(os.path.join(cur_dir, y_file))
                fh.write('\n')

        S.main([
            S.__name__,
            '-b', '-102.6562,23.3203,-73.8281,43.0078',
            '-s', '2005-01-01T00:00:00Z',
            '-e', '2005-01-01T23:59:59Z',
            '-x', 'TRMM_3B42_daily_precipitation_V6',
            '-y', 'TRMM_3B42_daily_precipitation_V7',
            '-f', self.opt_f,
            '-o', self.opt_o,
            '-l', self.opt_l,
        ], open('/dev/null', 'w'))

        # Verification Phase
        # --------------------------------------------------------------
        self.assertTrue(os.path.exists(self.opt_o))

        dataset = netCDF4.Dataset(self.opt_o)
        var_x = dataset.variables.get('x_TRMM_3B42_daily_precipitation_V6')
        var_y = dataset.variables.get('y_TRMM_3B42_daily_precipitation_V7')

        self.assertTrue(var_x)
        self.assertTrue(var_y)
        self.assertTrue('lon' in dataset.variables)
        self.assertTrue('lat' in dataset.variables)        
        self.assertTrue('sum_x' not in dataset.variables)
        self.assertTrue('sum_y' not in dataset.variables)
        self.assertTrue('correlation' not in dataset.variables)
        self.assertTrue('time_matched_difference' not in dataset.variables)
        self.assertTrue('offset' not in dataset.variables)
        self.assertTrue('slope' not in dataset.variables)
        self.assertTrue('n_samples' not in dataset.variables)
        
        assert_almost_equal(var_x[:].mean(), 0.85407738666696897)
        assert_almost_equal(var_y[:].mean(), 0.62942020454917991)

        isodate.parse_time(dataset.matched_start_time)
        isodate.parse_time(dataset.matched_end_time)
        self.assertEqual('daily', dataset.input_temporal_resolution)
 def parse_slot_request(self, data):
     start_date = parse_date(data["start_date"])
     end_date = parse_date(data["end_date"])
     start_time = parse_time(data["start_time"])
     end_time = parse_time(data["end_time"])
     week_day = data["week_day"]
     return RepeatingSlotRequest(
         week_day,
         start_date,
         end_date,
         start_time,
         end_time
     )
def parse_repeating_slot(data):
    start_date = parse_date(data["start_date"])
    end_date = parse_date(data["end_date"])
    start_time = parse_time(data["start_time"])
    end_time = parse_time(data["end_time"])
    week_day = data["week_day"]
    return RammetidSlot(
        week_day,
        start_date,
        end_date,
        start_time,
        end_time
    )
Esempio n. 5
0
    def from_data(cls, data):
        schedule_validator.validate(data)

        data.setdefault("minute", "*")
        data.setdefault("hour", "*")
        data.setdefault("day-of-month", "*")
        data.setdefault("month", "*")
        data.setdefault("day-of-week", "*")
        data.setdefault("begin", "00:00")
        data.setdefault("end", "23:59")

        return cls(data["minute"], data["hour"], data["day-of-month"], data["month"], data["day-of-week"],
                   isodate.parse_time(data["begin"]), isodate.parse_time(data["end"]))
 def parse_slot(self, data, application):
     start_date = parse_date(data["start_date"])
     end_date = parse_date(data["end_date"])
     start_time = parse_time(data["start_time"])
     end_time = parse_time(data["end_time"])
     week_day = data["week_day"]
     return RepeatingSlot(
         application,
         week_day,
         start_date,
         end_date,
         start_time,
         end_time
     )
Esempio n. 7
0
    def _validate_type_iso_time(self, time_value):
        is_valid = True
        if time_value == '24:00':
            return is_valid
        try:
            isodate.parse_time(time_value)
            if not re.match(
                    r'^([01]\d|2[0-3])\D?([0-5]\d)\D?([0-5]\d)?\D?(\d{3})?$',
                    time_value):
                is_valid = False
        except isodate.ISO8601Error as ex:
            is_valid = False

        if is_valid:
            return True
Esempio n. 8
0
    def _bind_processor(self, value):
        if value is None:
            return None

        if isinstance(value, str):
            value = isodate.parse_time(value)

        return value.isoformat()
Esempio n. 9
0
 def test_parse(self):
     '''
     Parse an ISO time string and compare it to the expected value.
     '''
     if expectation is None:
         self.assertRaises(ISO8601Error, parse_time, timestring)
     else:
         result = parse_time(timestring)
         self.assertEqual(result, expectation)
Esempio n. 10
0
def from_time(value):
    if isinstance(value, six.string_types):
        value = isodate.parse_time(value)

    if isinstance(value, datetime.time):
        return value.isoformat()
    else:
        raise ValueError('To create a proper string representation for a time,'
                         ' either a datetime.time or str has to be supplied!')
Esempio n. 11
0
 def test_parse(self):
     '''
     Parse an ISO time string and compare it to the expected value.
     '''
     if expectation is None:
         self.assertRaises(ISO8601Error, parse_time, timestring)
     else:
         result = parse_time(timestring)
         self.assertEqual(result, expectation)
Esempio n. 12
0
    def test_pythonvalue(self):
        instance = builtins.Time()
        value = datetime.time(21, 14, 42)
        assert instance.pythonvalue('21:14:42') == value

        value = datetime.time(21, 14, 42, 120000)
        assert instance.pythonvalue('21:14:42.120') == value

        value = isodate.parse_time('21:14:42.120+0200')
        assert instance.pythonvalue('21:14:42.120+0200') == value
 def _from(self, s):
     t = None
     try:
         t = isodate.parse_time(s)
     except ValueError:
         pass
     if not t:
         t = datetime.datetime.strptime(s, '%H:%M:%S')
         t = t.time()
     return t
Esempio n. 14
0
def validate_time(text):
    """
    Based on http://tools.ietf.org/html/rfc2425#section-5.8.4 and the fact
    that it specifies a subset of ISO 8601.

    @param text: String

    Examples:
    >>> validate_time('00:00:00')
    >>> validate_time('000000')
    >>> validate_time('01:02:03Z')
    >>> validate_time('01:02:03+01:30')
    >>> validate_time('01:02:60')
    Traceback (most recent call last):
    VCardFormatError: Invalid time (See RFC 2425 section 5.8.4 for time syntax)
    String: 01:02:60
    >>> validate_time('01:60:59')
    Traceback (most recent call last):
    VCardFormatError: Invalid time (See RFC 2425 section 5.8.4 for time syntax)
    String: 01:60:59
    >>> validate_time('24:00:00')
    Traceback (most recent call last):
    VCardFormatError: Invalid time (See RFC 2425 section 5.8.4 for time syntax)
    String: 24:00:00
    >>> validate_time('00:00:00Z+01') # doctest: +ELLIPSIS
    Traceback (most recent call last):
    VCardFormatError: Invalid time zone ...
    String: Z+01
    """
    time_timezone = VALID_TIME_TZ.match(text)
    if time_timezone is None:
        raise VCardFormatError(MSG_INVALID_TIME, {'String': text})

    time_str, timezone_str = time_timezone.groups()
    try:
        isodate.parse_time(time_str)
    except (isodate.ISO8601Error, ValueError):
        raise VCardFormatError(MSG_INVALID_TIME, {'String': text})

    if timezone_str == '':
        return

    validate_time_zone(timezone_str)
Esempio n. 15
0
def validate_time(text):
    """
    Based on http://tools.ietf.org/html/rfc2425#section-5.8.4 and the fact
    that it specifies a subset of ISO 8601.

    @param text: String

    Examples:
    >>> validate_time('00:00:00')
    >>> validate_time('000000')
    >>> validate_time('01:02:03Z')
    >>> validate_time('01:02:03+01:30')
    >>> validate_time('01:02:60') # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    VCardValueError: Invalid time (See RFC 2425 section 5.8.4 for time syntax)
    String: 01:02:60
    >>> validate_time('01:60:59') # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    VCardValueError: Invalid time (See RFC 2425 section 5.8.4 for time syntax)
    String: 01:60:59
    >>> validate_time('24:00:00') # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    VCardValueError: Invalid time (See RFC 2425 section 5.8.4 for time syntax)
    String: 24:00:00
    >>> validate_time('00:00:00Z+01') # doctest: +ELLIPSIS +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
    VCardValueError: Invalid time zone ...
    String: Z+01
    """
    time_timezone = VALID_TIME_WITH_TIMEZONE.match(text)
    if time_timezone is None:
        raise VCardValueError(NOTE_INVALID_TIME, {'String': text})

    time_str, timezone_str = time_timezone.groups()
    try:
        isodate.parse_time(time_str)
    except (isodate.ISO8601Error, ValueError):
        raise VCardValueError(NOTE_INVALID_TIME, {'String': text})

    if timezone_str == '':
        return

    validate_time_zone(timezone_str)
 def _from(self, s):
     t = None
     try:
         t = isodate.parse_time(s)
     except ValueError:
         pass
     if not t:
         t = datetime.datetime.strptime(s, '%H:%M:%S')
         t = t.time()
     return t
Esempio n. 17
0
    def test_pythonvalue(self):
        instance = builtins.Time()
        value = datetime.time(21, 14, 42)
        assert instance.pythonvalue('21:14:42') == value

        value = datetime.time(21, 14, 42, 120000)
        assert instance.pythonvalue('21:14:42.120') == value

        value = isodate.parse_time('21:14:42.120+0200')
        assert instance.pythonvalue('21:14:42.120+0200') == value
Esempio n. 18
0
 def to_python(self, value, context=None):
     if isinstance(value, datetime.time):
         return value
     try:
         return isodate.parse_time(value)
     except (isodate.ISO8601Error, TypeError):
         raise exceptions.ValidationError("Invalid time value '%s'" % value,
                                          value=value,
                                          invalid='format',
                                          against='time')
Esempio n. 19
0
 def to_python(self, value, context=None):
     if isinstance(value, datetime.time):
         return value
     try:
         return isodate.parse_time(value)
     except (isodate.ISO8601Error, TypeError):
         raise exceptions.ValidationError(
             "Invalid time value '%s'" % value,
             value=value,
             invalid='format',
             against='time'
         )
def add_entries_for_repeating_booking(result, repeating_bookings, start_date, end_date):
    for soknad in repeating_bookings:
        for slot in soknad['slots']:
            start_date_object = parse_date(slot['start_date'])
            end_date_object = parse_date(slot['end_date'])
            start_time = parse_time(slot['start_time'])
            end_time = parse_time(slot['end_time'])

            if start_date_object < start_date:
                start_date_object = start_date
            if end_date_object > end_date:
                end_date_object = end_date

            tmp_date = get_start_date_for_period(start_date_object, slot['week_day'])

            while tmp_date <= end_date_object:
                new_entry = get_soknad_fields_for_overview(soknad=soknad, date_object=tmp_date,
                                                           start_time=start_time.strftime("%H:%M"),
                                                           end_time=end_time.strftime("%H:%M"))
                result.append(new_entry)
                tmp_date += timedelta(weeks=1)
Esempio n. 21
0
 def to_python(self, value):
     """
     Validates that the input can be converted to a time. Returns a Python
     time.time object.
     """
     if value in forms.fields.EMPTY_VALUES:
         return None
     if isinstance(value, time):
         return value
     try:
         return isodate.parse_time(value)
     except (isodate.ISO8601Error, ValueError, TypeError):
         raise forms.ValidationError(self.error_messages['invalid'])
Esempio n. 22
0
 def to_python(self, value):
     """
     Validates that the input can be converted to a time. Returns a Python
     time.time object.
     """
     if value in forms.fields.EMPTY_VALUES:
         return None
     if isinstance(value, time):
         return value
     try:
         return isodate.parse_time(value)
     except (isodate.ISO8601Error, ValueError, TypeError):
         raise forms.ValidationError(self.error_messages['invalid'])
def from_datetimes(value, prop_type):

    if type(value) in constants.DATE_TYPES:
        return value

    if type(value) not in constants.BASE_STRING_TYPES:
        return None

    if prop_type == ndb.DateProperty:
        return isodate.parse_date(value)
    elif prop_type == ndb.DateTimeProperty:
        return isodate.parse_datetime(value).replace(tzinfo=None)
    elif prop_type == ndb.TimeProperty:
        return isodate.parse_time(value).replace(tzinfo=None)
Esempio n. 24
0
    def deserialize(self, value):
        """
        Deserialize the given string as a `~datetime.time`.

        Args:
            value (str): the string to deserialize.

        Returns:
            ~datetime.time: the deserialized date.
        """
        if self.format == 'iso8601':
            return isodate.parse_time(value)
        else:
            return datetime.datetime.strptime(value, self.format).time()
Esempio n. 25
0
def parse_datetime(datetimestring):
    '''
    Parses ISO 8601 date-times into datetime.datetime objects.
    This function uses parse_date and parse_time to do the job, so it allows
    more combinations of date and time representations, than the actual
    ISO 8601:2004 standard allows.
    '''
    try:
        datestring, timestring = re.split('T| ', datetimestring)
    except ValueError:
        raise isodate.ISO8601Error(
            "ISO 8601 time designator 'T' or ' '  missing. Unable to parse "
            "datetime string %r" % datetimestring)
    tmpdate = isodate.parse_date(datestring)
    tmptime = isodate.parse_time(timestring)
    return datetime.datetime.combine(tmpdate, tmptime)
Esempio n. 26
0
    def process_item(self, raw_item, spider):
        # map lastModified
        item = ItemAdapter(raw_item)
        if "lastModified" in item:
            try:
                item["lastModified"] = float(item["lastModified"])
            except:
                try:
                    date = dateutil.parser.parse(item["lastModified"])
                    item["lastModified"] = int(date.timestamp())
                except:
                    log.warning("Unable to parse given lastModified date " +
                                item["lastModified"])
                    del item["lastModified"]

        if "typicalLearningTime" in item["lom"]["educational"]:
            t = item["lom"]["educational"]["typicalLearningTime"]
            mapped = None
            splitted = t.split(":")
            if len(splitted) == 3:
                mapped = (int(splitted[0]) * 60 * 60 + int(splitted[1]) * 60 +
                          int(splitted[2]))
            if mapped is None:
                log.warning("Unable to map given typicalLearningTime " + t +
                            " to numeric value")
            item["lom"]["educational"]["typicalLearningTime"] = mapped
        if "technical" in item["lom"]:
            if "duration" in item["lom"]["technical"]:
                raw_duration = item["lom"]["technical"]["duration"]
                duration = raw_duration.strip()
                if duration:
                    if len(duration.split(":")) == 3:
                        duration = isodate.parse_time(duration)
                        duration = duration.hour * 60 * 60 + duration.minute * 60 + duration.second
                    elif duration.startswith("PT"):
                        duration = int(
                            isodate.parse_duration(duration).total_seconds())
                    else:
                        try:
                            duration = int(duration)
                        except:
                            duration = None
                            logging.warning(
                                "duration {} could not be normalized to seconds"
                                .format(raw_duration))
                    item["lom"]["technical"]["duration"] = duration
        return raw_item
Esempio n. 27
0
def iso8601_str_to_time(value, state=None):
    """Convert a clean string in ISO 8601 format to a time.

    .. note:: For a converter that doesn't require a clean string, see :func:`iso8601_input_to_time`.

    >>> iso8601_str_to_time(u'05:06:07')
    (datetime.time(5, 6, 7), None)
    >>> iso8601_str_to_time(u'T05:06:07')
    (datetime.time(5, 6, 7), None)
    >>> iso8601_str_to_time(u'05:06:07+01:00')
    (datetime.time(4, 6, 7), None)
    >>> iso8601_str_to_time(u'05:06:07-02:00')
    (datetime.time(7, 6, 7), None)
    >>> iso8601_str_to_time(u'05:06:07 +01:00')
    (datetime.time(4, 6, 7), None)
    >>> iso8601_str_to_time(u'05:06:07 -02:00')
    (datetime.time(7, 6, 7), None)
    >>> iso8601_str_to_time(u'05:06:07')
    (datetime.time(5, 6, 7), None)
    >>> iso8601_str_to_time(u'now')
    (u'now', u'Value must be a time in ISO 8601 format')
    >>> iso8601_str_to_time(u'')
    (u'', u'Value must be a time in ISO 8601 format')
    >>> iso8601_str_to_time(None)
    (None, None)
    """
    if value is None:
        return value, None
    if state is None:
        state = states.default_state
    # Parsing fails when time zone is preceded with a space. So we remove space before "+" and "-".
    while u' +' in value:
        value = value.replace(u' +', '+')
    while u' -' in value:
        value = value.replace(u' -', '-')
    try:
        value = isodate.parse_time(value)
    except isodate.ISO8601Error:
        return value, state._(u'Value must be a time in ISO 8601 format')
    if value.tzinfo is not None:
        # Convert time to UTC (using a temporary datetime).
        datetime_value = datetime.datetime.combine(datetime.date(2, 2, 2),
                                                   value)
        datetime_value = datetime_value.astimezone(
            pytz.utc).replace(tzinfo=None)
        value = datetime_value.time()
    return value, None
Esempio n. 28
0
 def deserialize(self, value):
     """
     Deserialize the given string as a `~datetime.time`.
     """
     if self.format == 'iso8601':
         try:
             return isodate.parse_time(value)
         except isodate.ISO8601Error:
             raise ValidationError('invalid ISO 8601 time', value=value)
     else:
         try:
             return datetime.datetime.strptime(value, self.format).time()
         except (TypeError, ValueError):
             raise ValidationError(
                 'invalid time, expected format {!r}'.format(self.format),
                 value=value,
             )
Esempio n. 29
0
def parse_datetime(datetimestring):
    '''
    Parses ISO 8601 date-times into datetime.datetime objects.
    This function uses parse_date and parse_time to do the job, so it allows
    more combinations of date and time representations, than the actual
    ISO 8601:2004 standard allows.
    '''
    try:
        datestring, timestring = re.split('T| ', datetimestring)
    except ValueError:
        raise isodate.ISO8601Error(
            "ISO 8601 time designator 'T' or ' '  missing. Unable to parse "
            "datetime string %r" % datetimestring
        )
    tmpdate = isodate.parse_date(datestring)
    tmptime = isodate.parse_time(timestring)
    return datetime.datetime.combine(tmpdate, tmptime)
Esempio n. 30
0
def userformdata_decode(s):
    if s.startswith(u'__date__@'):
        return isodate.parse_date(s[9:19])

    if s.startswith(u'__datetime__@'):
        return isodate.parse_datetime(s[13:32])

    if s.startswith(u'__time__@'):
        return isodate.parse_time(s[9:18])

    if s.startswith(u'__richtext__@'):
        data = json.loads(base64.b64decode(s[13:]))
        return RichTextValue(raw=data['raw'],
                             mimeType=data['mime'],
                             outputMimeType=data['output_mime'],
                             encoding=data['encoding'])

    return None
Esempio n. 31
0
def userformdata_decode(s):
    if s.startswith(u'__date__@'):
        return isodate.parse_date(s[9:19])

    if s.startswith(u'__datetime__@'):
        return isodate.parse_datetime(s[13:32])

    if s.startswith(u'__time__@'):
        return isodate.parse_time(s[9:18])

    if s.startswith(u'__richtext__@'):
        data = json.loads(base64.b64decode(s[13:]))
        return RichTextValue(
            raw=data['raw'],
            mimeType=data['mime'],
            outputMimeType=data['output_mime'],
            encoding=data['encoding']
        )

    return None
Esempio n. 32
0
def deserialize_data(o):
    if isinstance(o, dict) and set(o.keys()) == {'@type', '@value'}:
        o_type, o_value = o['@type'], o['@value']
        if o_type == 'uuid':
            return uuid.UUID(o_value)
        elif o_type == 'decimal':
            return decimal.Decimal(o_value)
        elif o_type == 'timedelta':
            return isodate.parse_duration(o_value)
        elif o_type == 'time':
            return isodate.parse_time(o_value)
        elif o_type == 'date':
            return isodate.parse_date(o_value)
        elif o_type == 'datetime':
            return isodate.parse_datetime(o_value)
    elif isinstance(o, dict):
        return {k: deserialize_data(v) for k, v in o.items()}
    elif isinstance(o, list):
        return [deserialize_data(v) for v in o]
    else:
        return o
Esempio n. 33
0
def userformdata_decode(string):
    if not isinstance(string, six.string_types):
        return string

    if string.startswith(u'__date__@'):
        return isodate.parse_date(string[9:])

    if string.startswith(u'__datetime__@'):
        return isodate.parse_datetime(string[13:])

    if string.startswith(u'__time__@'):
        return isodate.parse_time(string[9:])

    if string.startswith(u'__richtext__@'):
        data = json.loads(base64.b64decode(string[13:]))
        return RichTextValue(raw=data['raw'],
                             mimeType=data['mime'],
                             outputMimeType=data['output_mime'],
                             encoding=data['encoding'])

    return string
Esempio n. 34
0
 def getDatetime(self, attr):
     if not attr in self._datetime:
         content = self.getContent(attr)
         if content:
             try:
                 content = content.replace(' ', 'T')
                 if not 'T' in content:
                     if ':' in content:
                         value = isodate.parse_time(content)
                     else:
                         value = isodate.parse_date(content)
                 else:
                     value = isodate.parse_datetime(content)
                 if type(value) is datetime.time:
                     self._datetime[attr] = datetime.datetime.min.replace(hour=value.hour, minute=value.minute, second=value.second, microsecond=value.microsecond, tzinfo=value.tzinfo)
                 elif type(value) is datetime.date:
                     self._datetime[attr] = datetime.datetime(value.year, value.month, value.day, tzinfo=isodate.parse_tzinfo('Z'))
                 else:
                     self._datetime[attr] = value
             except isodate.ISO8601Error:
                 self._datetime[attr] = None
         elif attr in self.ATTR_DATETIME_FALLBACK:
             fallback_attr = self.ATTR_DATETIME_FALLBACK[attr]
             fallback_value = getattr(self, fallback_attr)
             if fallback_value and fallback_attr in self.ATTR_DATETIME_RELATION:
                 relation_attr = self.ATTR_DATETIME_RELATION[fallback_attr]
                 if relation_attr.startswith('+'):
                     relation_value = getattr(self, relation_attr[1:])
                     fallback_value = relation_value + fallback_value
                 elif relation_attr.startswith('-'):
                     relation_value = getattr(self, relation_attr[1:])
                     fallback_value = relation_value - fallback_value
                 else:
                     relation_value = getattr(self, relation_attr)
                     fallback_value += relation_value
             self._datetime[attr] = fallback_value
         else:
             self._datetime[attr] = None
     return self._datetime[attr]
Esempio n. 35
0
def userformdata_decode(string):
    if not isinstance(string, six.string_types):
        return string

    if string.startswith(u'__date__@'):
        return isodate.parse_date(string[9:])

    if string.startswith(u'__datetime__@'):
        return isodate.parse_datetime(string[13:])

    if string.startswith(u'__time__@'):
        return isodate.parse_time(string[9:])

    if string.startswith(u'__richtext__@'):
        data = json.loads(base64.b64decode(string[13:]))
        return RichTextValue(
            raw=data['raw'],
            mimeType=data['mime'],
            outputMimeType=data['output_mime'],
            encoding=data['encoding']
        )

    return string
Esempio n. 36
0
 def is_iso8601_time(self, to_validate: str) -> bool:
     try:
         return bool(isodate.parse_time(to_validate))
     except Exception:
         return False
Esempio n. 37
0
def time_format_checker(instance):
    if isinstance(instance, datetime.datetime):
        return True
    if isinstance(instance, six.string_types):
        return isodate.parse_time(instance)
Esempio n. 38
0
 def pythonvalue(self, value):
     return isodate.parse_time(value)
Esempio n. 39
0
 def end_time(self):
     if self.request.get('end_time'):
         return parse_time(self.request.get('end_time'))
     else:
         return None
 def _from_xml(self, e):
     s = str(e.text)
     t = isodate.parse_time(s)
     return t
Esempio n. 41
0
 def start_time(self):
     if self.request.get("start_time"):
         return parse_time(self.request.get("start_time"))
     else:
         return None
    def put(self, slot_id):
        try:
            slot = current_app.db_session.query(RepeatingSlot).filter(RepeatingSlot.id == slot_id).one()
        except NoResultFound:
            abort(404, __error__=[u"No slot found with id %d." % slot_id])

        ensure(PUT, slot)
        args = request.get_json()

        if slot.application.status != 'Granted':
            abort(400, __error__=[u'Kan ikke frigi tid når søknaden ikke er godkjent'])

        if slot.end_date <= date.today():
            abort(400, __error__=[u'Kan ikke frigi allerede brukt tid'])

        repeating_slots = []

        if "release_from_date" in args or "release_to_date" in args:
            release_from_date = parse_date(args["release_from_date"])
            release_to_date = parse_date(args["release_to_date"])

            if release_from_date > release_to_date:
                abort(400, __error__=[u'Startdato er etter sluttdato'])

            if release_from_date <= date.today():
                abort(400, __error__=[u'Kan kun frigi tid frem i tid'])

            if release_from_date <= slot.start_date and release_to_date >= slot.end_date:
                abort(400, __error__=[u'Du kan ikke frigi hele perioden'])

            intervals = [{
                "start": release_from_date - timedelta(days=1),
                "end": release_to_date + timedelta(days=1)
            }]
            periods = self.split_range_by_intervals(slot.start_date, slot.end_date, intervals)
            for period in periods:
                repeating_slots.append(RepeatingSlot(slot.application, slot.week_day,
                                                     period['start'], period['end'],
                                                     slot.start_time, slot.end_time, ))

        if "release_from_time" in args or "release_to_time" in args:
            release_from_time = parse_time(args["release_from_time"])
            release_to_time = parse_time(args["release_to_time"])
            if release_from_time > release_to_time:
                abort(400, __error__=[u'Starttidspunkt er etter slutttidspunkt'])

            if release_from_time <= slot.start_time and release_to_time >= slot.end_time:
                abort(400, __error__=[u'Du kan ikke frigi hele tidsperioden'])

            split_slot = slot
            if slot.start_date <= date.today():
                intervals = [{
                    "start": date.today(),
                    "end": date.today()
                }]
                periods = self.split_range_by_intervals(slot.start_date, slot.end_date, intervals)
                # add period for past
                repeating_slots.append(RepeatingSlot(slot.application, slot.week_day,
                                                     periods[0]['start'], periods[0]['end'],
                                                     slot.start_time, slot.end_time))
                # continue splitting the future
                split_slot = RepeatingSlot(slot.application, slot.week_day,
                                           periods[1]['start'], periods[1]['end'],
                                           slot.start_time, slot.end_time)

            intervals = [{
                "start": release_from_time,
                "end": release_to_time
            }]
            periods = self.split_range_by_intervals(split_slot.start_time, split_slot.end_time, intervals)
            for period in periods:
                repeating_slots.append(RepeatingSlot(split_slot.application, split_slot.week_day,
                                                     split_slot.start_date + timedelta(days=1), split_slot.end_date,
                                                     period['start'], period['end']))

        # Remove old slot if new slots are generated
        if len(repeating_slots) > 0:
            current_app.db_session.delete(slot)

        # Add new slot(s)
        for repeating_slot in repeating_slots:
            current_app.db_session.add(repeating_slot)
        current_app.db_session.commit()

        return repeating_slots, 200
Esempio n. 43
0
def new_duracion(clip):
    t = parse_time(clip['duracion'])
    return timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)
Esempio n. 44
0
def to_time(value):
    return isodate.parse_time(value)
Esempio n. 45
0
    def to_python(self) -> float:
        """ """
        self._validate()

        return isodate.parse_time(self)
Esempio n. 46
0
def time_format_checker(instance):
    if isinstance(instance, datetime.datetime):
        return True
    if isinstance(instance, six.string_types):
        return isodate.parse_time(instance)
Esempio n. 47
0
 def _from_xml(self, e):
     s = str(e.text)
     t = isodate.parse_time(s)
     return t
Esempio n. 48
0
 def start_time(self):
     if self.request.get('start_time'):
         return parse_time(self.request.get('start_time'))
     else:
         return None
Esempio n. 49
0
 def end_time(self):
     if self.request.get("end_time"):
         return parse_time(self.request.get("end_time"))
     else:
         return None
Esempio n. 50
0
 def validate_Time(self, value, context=''):
     try:
         isodate.parse_time(value)
         return True
     except:
         return False
Esempio n. 51
0
 def _result_processor(self, value):
     try:
         return isodate.parse_time(value)
     except Exception:
         return datetime.time()
Esempio n. 52
0
 def pythonvalue(self, value):
     return isodate.parse_time(value)
Esempio n. 53
0
 def _parse(self, val):
     return isodate.parse_time(val)