def build_sub_event_time_ranges(self, start_date, end_date, time_tables):
        sub_event_time_ranges = []

        for time_table in time_tables:
            current_date = start_date
            weekday = int(time_table.get('weekday'))
            start_time = parse_time(time_table.get('starttime'))
            end_time = parse_time(time_table.get('endtime'))
            repetition = int(time_table.get('repetition'))
            if repetition == 0:
                repetition = 7  # assume repetition 0 and 7 mean the same thing

            if not (weekday and repetition) or start_time >= end_time:
                continue

            while current_date.isoweekday() != weekday:
                current_date += timedelta(days=1)

            while current_date <= end_date:
                sub_event_time_ranges.append(SubEventTimeRange(
                    datetime.combine(current_date, start_time).astimezone(TIMEZONE),
                    datetime.combine(current_date, end_time).astimezone(TIMEZONE),
                ))
                current_date += timedelta(days=repetition)

        return sub_event_time_ranges
Пример #2
0
    def setUpTestData(cls):
        daily_timeslot = TimeSlot.objects.create(
            name="thursday full day",
            weekday_start=4,
            weekday_end=4,
            hour_start=dateparse.parse_time("8:0:0"),
            hour_end=dateparse.parse_time("23:0:0"),
        )
        reduced_timeslot = TimeSlot.objects.create(
            name="thursday reduced",
            weekday_start=4,
            weekday_end=4,
            hour_start=dateparse.parse_time("14:0:0"),
            hour_end=dateparse.parse_time("20:0:0"),
        )

        fablab_role = Role.objects.create(
            name="Fablab Access",
            role_kind=0
        )
        fablab_role.time_slots.add(daily_timeslot)

        guest_role = Role.objects.create(
            name="Guest Access",
            role_kind=0
        )
        guest_role.time_slots.add(reduced_timeslot)

        fab_guest_group = Group.objects.create(name="Fablab Guest")
        fab_guest_group.roles.add(fablab_role, guest_role)
        guest_group = Group.objects.create(name="Guest")
        guest_group.roles.add(guest_role)

        card = Card.objects.create(nfc_id=123456)
        user = User.objects.create(username="******")
        u = UserProfile.objects.create(
            user=user,
            card=card,
            name="Alessandro Monaco",
            needSubscription=False,
            endSubscription=timezone.now()
        )
        u.groups.add(guest_group)

        category = Category.objects.create(
            name="category"
        )

        device = Device.objects.create(
            name="device",
            hourlyCost=1.0,
            category=category,
            mac="00:00:00:00:00:00"
        )

        cls.card = card
        cls.userprofile = u
        cls.device = device
Пример #3
0
 def test_parse_time(self):
     # Valid inputs
     self.assertEqual(parse_time('09:15:00'), time(9, 15))
     self.assertEqual(parse_time('10:10'), time(10, 10))
     self.assertEqual(parse_time('10:20:30.400'), time(10, 20, 30, 400000))
     self.assertEqual(parse_time('4:8:16'), time(4, 8, 16))
     # Invalid inputs
     self.assertEqual(parse_time('091500'), None)
     self.assertRaises(ValueError, parse_time, '09:15:90')
Пример #4
0
 def end_date(self):
     value = self.getData()
     if dateparse.parse_datetime(value) is not None:
         self.addObject(dateparse.parse_datetime(value))
     elif dateparse.parse_date(value) is not None:
         self.addObject(dateparse.parse_date(value))
     elif dateparse.parse_time(value) is not None:
         self.addObject(dateparse.parse_time(value))
     else:
         raise ValueError('"{0}" is not a valid datetime'.format(value))
Пример #5
0
def _pop_time_kwargs(dataset):
    day, begin, end = dataset.pop('time')
    d = DAYS[day - 1]

    b_dt = datetime.datetime.combine(d, parse_time(begin))
    e_dt = datetime.datetime.combine(d, parse_time(end))
    return {
        'begin_time': Time.objects.get_or_create(value=cst.localize(b_dt))[0],
        'end_time': Time.objects.get_or_create(value=cst.localize(e_dt))[0],
    }
Пример #6
0
    def _spot_availability_from_data(self, avaliblity_data):
        availability = []

        for day in avaliblity_data:
            for hours in avaliblity_data[day]:
                available_hours = SpotAvailableHours()
                available_hours.day = day
                available_hours.start_time = parse_time(hours[0])
                available_hours.end_time = parse_time(hours[1])
                availability.append(available_hours)
        return availability
Пример #7
0
 def get_value(self, condition, value, request=None):
     if isinstance(value, six.string_types):
         value = parse_time(value)
     elif isinstance(value, (list, tuple)):
         _value = list(set([ parse_time(v) for v in value ]))
         if len(_value) == len(value):
             value = _value
         else:
             value = None
     if value is None:
         raise ValueError('One or more values not valid in `%s` filter.' % force_text(self))
     if condition == 'range':
         value = [min(value), max(value)]
     return value
Пример #8
0
def deserialize_instance(model, data):
    ret = model()
    for k, v in data.items():
        is_db_value = False
        if k.startswith(SERIALIZED_DB_FIELD_PREFIX):
            k = k[len(SERIALIZED_DB_FIELD_PREFIX):]
            is_db_value = True
        if v is not None:
            try:
                f = model._meta.get_field(k)
                if isinstance(f, DateTimeField):
                    v = dateparse.parse_datetime(v)
                elif isinstance(f, TimeField):
                    v = dateparse.parse_time(v)
                elif isinstance(f, DateField):
                    v = dateparse.parse_date(v)
                elif isinstance(f, BinaryField):
                    v = force_bytes(base64.b64decode(force_bytes(v)))
                elif is_db_value:
                    try:
                        # This is quite an ugly hack, but will cover most
                        # use cases...
                        v = f.from_db_value(v, None, None, None)
                    except Exception:
                        raise ImproperlyConfigured(
                            "Unable to auto serialize field '{}', custom"
                            " serialization override required".format(k))
            except FieldDoesNotExist:
                pass
        setattr(ret, k, v)
    return ret
    def to_python(cls, value, **kwargs):
        parsed = parse_time(force_str(value))
        if parsed is None:
            raise cls.exception(
                "Value {0} cannot be converted to a time object".format(value))

        return parsed
Пример #10
0
    def from_native(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        if isinstance(value, datetime.time):
            return value

        for format in self.input_formats:
            if format.lower() == ISO_8601:
                try:
                    parsed = parse_time(value)
                except (ValueError, TypeError):
                    pass
                else:
                    if parsed is not None:
                        return parsed
            else:
                try:
                    parsed = datetime.datetime.strptime(value, format)
                except (ValueError, TypeError):
                    pass
                else:
                    return parsed.time()

        msg = self.error_messages["invalid"] % readable_time_formats(
            self.input_formats)
        raise ValidationError(msg)
Пример #11
0
    def _mirror_data_from_stormpath_account(self, account):
        for field in self.STORMPATH_BASE_FIELDS:
            # The password is not sent via the API
            # so we take care here to not try and
            # mirror it because it's not there
            if field != 'password':
                self.__setattr__(field, account[field])
        for key in account.custom_data.keys():
            field_name = [part for part in key.split(self.DJANGO_PREFIX) if part][0]
            value = account.custom_data[key]
            # check if value is not None for nullable fields
            if value:
                if field_name in self.DATE_FIELDS:
                    value = parse_date(value)
                elif field_name in self.DATETIME_FIELDS:
                    value = parse_datetime(value)
                elif field_name in self.TIME_FIELDS:
                    value = parse_time(value)
            self.__setattr__(field_name, value)

        if account.status == account.STATUS_ENABLED:
            self.is_active = True
            self.is_verified = not get_default_is_active()
        else:
            self.is_active = False
            if account.status == account.STATUS_UNVERIFIED:
                self.is_verified = False
Пример #12
0
 def parse(cls, raw_value):
     if isinstance(raw_value, cls.dtype):
         return raw_value
     value = parse_time(raw_value)
     if value is not None:
         return value
     raise ValueError("Could not parse ISO time from '%s'."%raw_value)
Пример #13
0
 def parse(cls, raw_value):
     if isinstance(raw_value, cls.dtype):
         return raw_value
     value = parse_time(raw_value)
     if value is not None:
         return value
     raise ValueError("Could not parse ISO time from '%s'." % raw_value)
Пример #14
0
def deserialize_instance(model, data):
    ret = model()
    for k, v in data.items():
        is_db_value = False
        if k.startswith(SERIALIZED_DB_FIELD_PREFIX):
            k = k[len(SERIALIZED_DB_FIELD_PREFIX) :]
            is_db_value = True
        if v is not None:
            try:
                f = model._meta.get_field(k)
                if isinstance(f, DateTimeField):
                    v = dateparse.parse_datetime(v)
                elif isinstance(f, TimeField):
                    v = dateparse.parse_time(v)
                elif isinstance(f, DateField):
                    v = dateparse.parse_date(v)
                elif isinstance(f, BinaryField):
                    v = force_bytes(base64.b64decode(force_bytes(v)))
                elif is_db_value:
                    try:
                        # This is quite an ugly hack, but will cover most
                        # use cases...
                        v = f.from_db_value(v, None, None, None)
                    except:
                        raise ImproperlyConfigured(
                            "Unable to auto serialize field '{}', custom" " serialization override required".format(k)
                        )
            except FieldDoesNotExist:
                pass
        setattr(ret, k, v)
    return ret
Пример #15
0
    def from_native(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        if isinstance(value, datetime.time):
            return value

        for format in self.input_formats:
            if format.lower() == ISO_8601:
                try:
                    parsed = parse_time(value)
                except (ValueError, TypeError):
                    pass
                else:
                    if parsed is not None:
                        return parsed
            else:
                try:
                    parsed = datetime.datetime.strptime(value, format)
                except (ValueError, TypeError):
                    pass
                else:
                    return parsed.time()

        msg = self.error_messages["invalid"] % readable_time_formats(self.input_formats)
        raise ValidationError(msg)
Пример #16
0
def report_hook(obj):
    if '__type__' in obj:
        if obj['__type__'] == 'datetime':
            return parse_datetime(obj['datetime'])
        elif obj['__type__'] == 'time':
            return parse_time(obj['time'])
    else:
        return obj
Пример #17
0
    def test_user_can_use_device_role_not_categories(self):
        timeslot = TimeSlot.objects.create(
            name="any day",
            weekday_start=1,
            weekday_end=7,
            hour_start=dateparse.parse_time("00:00:00"),
            hour_end=dateparse.parse_time("23:59:59"),
        )

        role = Role.objects.create(name="role", )
        role.time_slots.add(timeslot)

        group = Group.objects.create(name="group")
        group.roles.add(role)
        self.noperm_userprofile.groups.add(group)
        self.assertFalse(
            self.noperm_userprofile.can_use_device_now(self.device))
Пример #18
0
def set_time(timestamp: datetime, new_time: str):
    new_time = parse_time(new_time)
    return timestamp.replace(
        hour=new_time.hour,
        minute=new_time.minute,
        second=new_time.second,
        microsecond=new_time.microsecond,
    )
Пример #19
0
 def time(self, value):
     # type: (Text) -> dt.time
     parsed_value = parse_time(value)  # type: Optional[dt.time]
     if parsed_value is not None:
         return parsed_value
     raise EnvironmentCastError(
         "Could not parse value {0!r} into a datetime.time".format(value)
     )
Пример #20
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data()
     context['date'] = parse_date(self.kwargs['date'])
     context['time'] = parse_time(self.kwargs['time'])
     context['court'] = self.kwargs['court']
     context['person'] = person_from_user(self.request)
     context['can_edit'] = True
     context['buttons'] = [Button('Save'), Button('Back')]
     return context
Пример #21
0
def account(request):
    SelectBuildingFormSet = formset_factory(forms.SelectBuildingForm,
                                            extra=max_num_excursions,
                                            max_num=max_num_excursions)

    # userchange form
    if request.method == "POST" and 'username_change' in request.POST:
        form_userchange = forms.CustomUserChangeForm(request.POST,
                                                     instance=request.user)
        if form_userchange.is_valid():
            form_userchange.save(commit=True)
            print("  ***username changed***")
            return redirect("Hydroxychloroquine-account")
    else:
        form_userchange = forms.CustomUserChangeForm(instance=request.user)

    # formset_SelectBuilding
    if request.method == "POST" and 'add_buildings' in request.POST:
        formset_SelectBuilding = SelectBuildingFormSet(request.POST,
                                                       prefix="excursions")
        formset_SelectBuilding_valid = any(form.is_valid()
                                           for form in formset_SelectBuilding)
        for form in formset_SelectBuilding:
            if form.is_valid() and len(form.cleaned_data['days_selected']):
                e = models.Excursion.objects.create(
                    user_id=request.user,
                    building_id=form.cleaned_data['building_id'],
                    start_time=utils.convert_to_24_hour_time(
                        form.cleaned_data['start_time']),
                    end_time=utils.convert_to_24_hour_time(
                        form.cleaned_data['end_time']),
                    days_selected="".join(form.cleaned_data['days_selected']),
                )
                print("  ***excursion object made***  excursion =", e)
        return redirect("Hydroxychloroquine-account")
    else:
        formset_SelectBuilding = SelectBuildingFormSet(prefix="excursions")

    # need to pass time choices directly
    times = [
        "{}:00{}".format(h, ap) for ap in ("am", "pm")
        for h in ([12] + list(range(1, 12)))
    ]
    time_choices = [(t, parse_time(utils.convert_to_24_hour_time(t)))
                    for i, t in enumerate(times, start=1)]

    users_excursions = models.Excursion.objects.filter(
        user_id=request.user).filter(report_id=None)
    context = {
        "title": "Account",
        "loop_max": len(formset_SelectBuilding) - 1,
        "form_userchange": form_userchange,
        "formset_SelectBuilding": formset_SelectBuilding,
        "users_excursions": users_excursions,
        "time_choices": time_choices,
    }
    return render(request, "Hydroxychloroquine/account.html", context)
Пример #22
0
 def test_parse_time(self):
     # Valid inputs
     self.assertEqual(parse_time('09:15:00'), time(9, 15))
     self.assertEqual(parse_time('10:10'), time(10, 10))
     self.assertEqual(parse_time('10:20:30.400'), time(10, 20, 30, 400000))
     self.assertEqual(parse_time('10:20:30,400'), time(10, 20, 30, 400000))
     self.assertEqual(parse_time('4:8:16'), time(4, 8, 16))
     # Invalid inputs
     self.assertIsNone(parse_time('091500'))
     with self.assertRaises(ValueError):
         parse_time('09:15:90')
def populate(apps, schema_editor):
    tz = get_current_timezone()

    output_device_model = apps.get_model('crop', 'OutputDevice')
    output_device_task_model = apps.get_model('crop',
                                              'OutputDeviceScheduledTask')
    crop_model = apps.get_model('crop', 'Crop')
    plan_model = apps.get_model('crop', 'GrowthPlan')
    tray_model = apps.get_model('crop', 'Tray')

    device1 = output_device_model.objects.create(name='LED Light',
                                                 device_type=1,
                                                 units=2,
                                                 units_per_second=1)

    device2 = output_device_model.objects.create(name='Water sprayer',
                                                 device_type=2,
                                                 units=1,
                                                 units_per_second=1)

    device_task = output_device_task_model.objects.create(
        output_device=device1,
        start_time=parse_time('16:00:00'),
        end_time=parse_time('18:00:00'))

    device_task = output_device_task_model.objects.create(
        output_device=device2,
        start_time=parse_time('12:00:00'),
        end_time=parse_time('18:00:00'))

    crop = crop_model.objects.create(name='New Basil', family='Basil')

    plan = plan_model.objects.create(crop=crop,
                                     name='Micro',
                                     growth_duration=8,
                                     est_yield=80)

    plan.output_devices.set([device1, device2])

    tray_model.objects.create(
        crop=crop,
        growth_plan=plan,
        sow_date=tz.localize(parse_datetime('2020-1-22T12:00:00')),
        harvest_date=tz.localize(parse_datetime('2020-1-29T12:00:00')))
Пример #24
0
 def _decoder(cls, obj):
     custom_data = cls._parse_custom_obj(obj)
     if custom_data:
         if custom_data[0] == 'datetime':
             return parse_datetime(custom_data[1])
         elif custom_data[0] == 'date':
             return parse_date(custom_data[1])
         elif custom_data[0] == 'time':
             return parse_time(custom_data[1])
     return obj
Пример #25
0
def time_or_none(value, expect):
    value = string_or_none(value, expect)

    if value is not None:
        clean = dateparse.parse_time(value)
        if clean is None:
            raise ValueError('Could not parse time: %s' % value)
        value = clean

    return value
Пример #26
0
def time_or_none(value, expect):
    value = string_or_none(value, expect)

    if value is not None:
        clean = dateparse.parse_time(value)
        if clean is None:
            raise ValueError('Could not parse time: %s' % value)
        value = clean

    return value
Пример #27
0
 def _deserialize(type_, value):
     if type_ == FlowResponse.Type.URL:
         return URL(value)
     elif type_ == FlowResponse.Type.DATETIME:
         return dateparse.parse_datetime(value)
     elif type_ == FlowResponse.Type.DATE:
         return dateparse.parse_date(value)
     elif type_ == FlowResponse.Type.TIME:
         return dateparse.parse_time(value)
     return value
Пример #28
0
    def test_is_valid_time_in_rule_border_cross(self):
        rule = ReservationRule(machine_type=self.machine_type,
                               start_time=parse_time("10:00"),
                               days_changed=1,
                               end_time=parse_time("6:00"),
                               start_days=[Day.MONDAY],
                               max_hours=10,
                               max_inside_border_crossed=5)

        self.assertTrue(
            rule.valid_time_in_rule(parse_datetime("2018-11-05 08:00"),
                                    parse_datetime("2018-11-05 12:00"), True))
        self.assertTrue(
            rule.valid_time_in_rule(parse_datetime("2018-11-05 00:00"),
                                    parse_datetime("2018-11-05 15:00"), True))

        self.assertFalse(
            rule.valid_time_in_rule(parse_datetime("2018-11-05 09:00"),
                                    parse_datetime("2018-11-05 16:00"), True))
Пример #29
0
def split_tzname_delta(tzname):
    """
    Split a time zone name into a 3-tuple of (name, sign, offset).
    """
    for sign in ["+", "-"]:
        if sign in tzname:
            name, offset = tzname.rsplit(sign, 1)
            if offset and parse_time(offset):
                return name, sign, offset
    return tzname, None, None
Пример #30
0
    def test_is_valid_time_no_rules(self):
        """
        Tests to check that `ReservationRule.valid_time` works correctly when there are no rules or a period is not
        covered by any rules.
        """
        start_time = parse_datetime("2021-03-03 12:00")
        end_time = start_time + timedelta(hours=6)
        is_valid = ReservationRule.valid_time(start_time, end_time,
                                              self.machine_type)
        self.assertFalse(
            is_valid, "A period should not be valid if there are no rules.")

        # `Day.values` is a list of all the weekdays
        rule1 = ReservationRule.objects.create(
            machine_type=self.machine_type,
            start_time=parse_time("10:00"),
            days_changed=0,
            end_time=parse_time("11:00"),
            start_days=Day.values,
            max_hours=10,
            max_inside_border_crossed=5,
        )
        is_valid = ReservationRule.valid_time(start_time, end_time,
                                              self.machine_type)
        self.assertFalse(
            is_valid,
            "A period should not be valid if it is not covered by any rules.")

        rule1.start_time = parse_time("12:00")
        rule1.end_time = parse_time("18:00")
        rule1.save()
        self.assertTrue(
            ReservationRule.valid_time(start_time, end_time,
                                       self.machine_type))

        # Create an empty period
        start_time = parse_datetime("2021-03-01 12:05")
        is_valid = ReservationRule.valid_time(start_time, start_time,
                                              self.machine_type)
        self.assertFalse(
            is_valid,
            "A period should not be valid if it is empty, i.e., not coverd by any rules."
        )
Пример #31
0
def sharer_search_ride(request):
    if request.method == 'GET':
        queryset_list = Ride.objects.order_by('-arrival_time_owner').filter(
            is_confirmed=False)
        # Destination input
        if 'destination_sharer' in request.GET:
            destination_sharer = request.GET['destination_sharer']
            if destination_sharer:
                queryset_list = queryset_list.filter(
                    destination_owner__icontains=destination_sharer)
        if 'city' in request.GET:
            city = request.GET['city']
            if city:
                queryset_list = queryset_list.filter(
                    destination_owner__icontains=city)
        if 'state' in request.GET:
            state = request.GET['state']
            if state:
                queryset_list = queryset_list.filter(
                    destination_owner__icontains=state)
        # Arrival time window
        if 'arrival_date' in request.GET:
            arrival_date = parse_date(request.GET['arrival_date'])
        if 'arrival_time' in request.GET:
            arrival_time = parse_time(request.GET['arrival_time'])
        queryset_list = queryset_list.filter(
            arrival_time_owner__date=arrival_date)
        queryset_list = queryset_list.filter(is_shareable=True)
        queryset_list = [
            query for query in queryset_list
            if (query.owner_id != request.GET['sharer_id'])
        ]

        context = {
            'rides':
            queryset_list,
            'sharer_name':
            request.GET['sharer_first_name'] + ' ' +
            request.GET['sharer_last_name'],
            'sharer_id':
            request.GET['sharer_id'],
            'sharer_email':
            request.GET['sharer_email'],
            'destination_sharer':
            request.GET['destination_sharer'] + ', ' + request.GET['city'] +
            ', ' + request.GET['state'],
            'passengers_sharer':
            request.GET['passengers_sharer'],
            'arrival_time':
            request.GET['arrival_time'],
            'arrival_date':
            request.GET['arrival_date'],
        }
        return render(request, 'rides/sharer_search_ride.html', context)
Пример #32
0
 def object_hook(cls, d):
     s = d.get('@_data_')
     if s:
         dt = d.get('@_type_')
         if dt == 'datetime':
             return parse_datetime(s)
         elif dt == 'date':
             return parse_date(s)
         elif dt == 'time':
             return parse_time(s)
     return d
Пример #33
0
def deserialize_by_field(value, field):
    """
    Some types get serialized to JSON, as strings.
    If we know what they are supposed to be, we can deserialize them
    """
    if isinstance(field, forms.DateTimeField):
        value = parse_datetime(value)
    elif isinstance(field, forms.DateField):
        value = parse_date(value)
    elif isinstance(field, forms.TimeField):
        value = parse_time(value)
    return value
Пример #34
0
def salvarHora(request):

    listaID = request.GET.get('lista', None)
    hora = parse_time(request.GET.get('hora', None))

    lista = Lista.objects.get(pk=listaID)
    lista.hora = hora
    lista.save()

    gerar_acao(request.user.funcionario, "Edição", "Lista", listaID)
    data = {'erro': False}
    return JsonResponse(data)
Пример #35
0
def excel_cell_to_time(v, datemode=0):
    try:
        if isinstance(v, (str, unicode)):
            return parse_time(v)
        elif isinstance(v, float):
            t = xlrd.xldate_as_tuple(v, datemode)
            return datetime.time(t[3], t[4], t[5])
        else:
            return None
    except:
        traceback.print_exc()
        return None
Пример #36
0
    def get_or_init_instance(self, instance_loader, row):
        instance, create = super(LiturgyResource, self).get_or_init_instance(instance_loader, row)

        # get_or_create the service
        name, time = row.get('service__name'), row.get('service__time')
        try:
            time = parse_time(time)
        except (TypeError, ValueError):
            raise ValueError(_('Could not parse time %s. Make sure that the '
                               '`service__time` field is formatted as text.') % time)
        instance.service, created = Service.objects.get_or_create(name=name, time=time)
        return instance, create
Пример #37
0
def teacher(request, teacher_id):
    t = Teachers.objects.get(teacher_id=teacher_id)
    m = Meeting.objects.filter(teacher=t.teacher_id, meeting_status=1)
    if request.method == 'POST':
        begin = parse_time(request.POST.get('begin', ''))
        end = parse_time(request.POST.get('end', ''))
        dif_beg = datetime.combine(date.min, begin) - datetime.combine(
            date.min, t.free_beg)
        t.free_beg = begin
        t.free_end = end
        t.save()
        for obj in m:
            new_time = (datetime.combine(date.min, obj.meeting_time) +
                        dif_beg).time()
            if begin > new_time or new_time > end:
                del_obj = Meeting.objects.get(meeting_id=obj.meeting_id)
                del_obj.delete()
                # obj.delete()
            else:
                obj.meeting_time = new_time
                obj.save()
    return render(request, 'teacher.html', {'teacher': t, 'meeting': m})
Пример #38
0
    def test_implicit_date_filters(self):
        john = Person.objects.get(name="John")
        # Mark was created at least one second after John.
        mark = Person.objects.get(name="Mark")

        from rest_framework import serializers
        from rest_framework.renderers import JSONRenderer

        class PersonSerializer(serializers.ModelSerializer):
            class Meta:
                model = Person

        # Figure out what the date strings should look like based on the
        # serializer output.
        data = PersonSerializer(john).data

        date_str = JSONRenderer().render(data["date_joined"]).decode("utf-8").strip('"')

        # Adjust for imprecise rendering of time
        datetime_str = (
            JSONRenderer()
            .render(parse_datetime(data["datetime_joined"]) + datetime.timedelta(seconds=0.6))
            .decode("utf-8")
            .strip('"')
        )

        # Adjust for imprecise rendering of time
        dt = datetime.datetime.combine(datetime.date.today(), parse_time(data["time_joined"])) + datetime.timedelta(
            seconds=0.6
        )
        time_str = JSONRenderer().render(dt.time()).decode("utf-8").strip('"')

        # DateField
        GET = {"date_joined__lte": date_str}
        f = AllLookupsPersonDateFilter(GET, queryset=Person.objects.all())
        self.assertEqual(len(list(f)), 2)
        p = list(f)[0]

        # DateTimeField
        GET = {"datetime_joined__lte": datetime_str}
        f = AllLookupsPersonDateFilter(GET, queryset=Person.objects.all())
        self.assertEqual(len(list(f)), 1)
        p = list(f)[0]
        self.assertEqual(p.name, "John")

        # TimeField
        GET = {"time_joined__lte": time_str}
        f = AllLookupsPersonDateFilter(GET, queryset=Person.objects.all())
        self.assertEqual(len(list(f)), 1)
        p = list(f)[0]
        self.assertEqual(p.name, "John")
Пример #39
0
class Appointment(models.Model):
    patient = models.ForeignKey(Patient, verbose_name='patient', blank=False)
    doctor = models.ForeignKey(Doctor, verbose_name='doctor', blank=False)
    date = models.DateField('physician acceptance date', blank=False, null=True)
    hour = models.TimeField('physician acceptance time', blank=False, null=True)
    TIME_CHOICES = (
        (dateparse.parse_time('09:00')),
        (dateparse.parse_time('10:00')),
        (dateparse.parse_time('11:00')),
        (dateparse.parse_time('12:00')),
        (dateparse.parse_time('13:00')),
        (dateparse.parse_time('14:00')),
        (dateparse.parse_time('15:00')),
        (dateparse.parse_time('16:00')),
        (dateparse.parse_time('17:00')),
    )
    
    def __str__(self):
        return "%s %s - %s" % (self.date, self.hour, self.doctor)
Пример #40
0
def set_time(request):
    """
    Set a time to a People.

    Accept only POST request with parameters:
    :arg int num:
        The bib number of the runner
    :arg str/time time:
        A time format (like hh:mm:ss)

    :returns:
        A JSON data with some runner informations.
    """
    # sanity checks
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])

    for param in ('num', 'time'):
        if param not in request.POST:
            return HttpResponseBadRequest('missing parameter %r' % param)
    try:
        num = int(request.POST['num'])
    except ValueError:
        return HttpResponseBadRequest('num must be an integer')

    try:
        time = parse_time(request.POST['time'])
        if not time:
            raise ValueError
    except ValueError:
        return HttpResponseBadRequest('"time" must be HH:MM[:ss[.uuuuuu]]')

    try:
        runner = People.objects.filter(num=num).get()
    except People.DoesNotExist:
        return HttpResponseBadRequest('runner with number %s is unknown' % num)

    runner.time = timedelta(days=0, minutes=time.minute, seconds=time.second)
    runner.save()

    response = {
        'first_name': runner.first_name,
        'last_name': runner.last_name,
        'num': runner.num,
        'time': str(runner.time),
    }

    return HttpResponse(json.dumps(response),
                        status=http.HTTPStatus.CREATED,
                        content_type='application/json')
Пример #41
0
    def test_implicit_date_filters(self):
        john = Person.objects.get(name="John")
        # Mark was created at least one second after John.
        # mark = Person.objects.get(name="Mark")

        # Figure out what the date strings should look like based on the
        # serializer output.
        data = PersonSerializer(john).data

        date_str = JSONRenderer().render(
            data['date_joined']).decode('utf-8').strip('"')

        # Adjust for imprecise rendering of time
        offset = parse_datetime(
            data['datetime_joined']) + datetime.timedelta(seconds=0.6)
        datetime_str = JSONRenderer().render(offset)
        datetime_str = datetime_str.decode('utf-8').strip('"')

        # Adjust for imprecise rendering of time
        offset = datetime.datetime.combine(today,
                                           parse_time(data['time_joined']))
        offset += datetime.timedelta(seconds=0.6)
        time_str = JSONRenderer().render(
            offset.time()).decode('utf-8').strip('"')

        # DateField
        GET = {
            'date_joined__lte': date_str,
        }
        f = PersonFilter(GET, queryset=Person.objects.all())
        self.assertEqual(len(list(f.qs)), 2)
        p = list(f.qs)[0]

        # DateTimeField
        GET = {
            'datetime_joined__lte': datetime_str,
        }
        f = PersonFilter(GET, queryset=Person.objects.all())
        self.assertEqual(len(list(f.qs)), 1)
        p = list(f.qs)[0]
        self.assertEqual(p.name, "John")

        # TimeField
        GET = {
            'time_joined__lte': time_str,
        }
        f = PersonFilter(GET, queryset=Person.objects.all())
        self.assertEqual(len(list(f.qs)), 1)
        p = list(f.qs)[0]
        self.assertEqual(p.name, "John")
Пример #42
0
    def filter_availability(self, occupancy_schedule):

        z = []
        for o in occupancy_schedule:
            start_time = parse_time(o['start_time'])

            duration = parse_duration(o['end_time'])
            qo = self.exclude(start__iso_week_day=o['weekday'],
                              start__time__gte=start_time,
                              end__date__lte=F('start__time') + duration)
            z.append(qo.values_list('id', flat=True))

        queryset = self.filter(id__in=z)
        return queryset
Пример #43
0
def create_talon(request):
    data = request.POST

    street = data.get('street')
    house = data.get('building')
    address = get_object_or_404(Address, street=street, house=house)

    doctor_id = data.get('doctorId')
    doctor = get_object_or_404(Doctor, id=doctor_id)

    birth_day = data.get('dob-day')
    birth_month = data.get('dob-month')
    birth_year = data.get('dob-year')

    time_talon = parse_time(data.get('time'))
    date_talon = parse_date(data.get('date'))

    date_of_receipt = datetime.datetime.combine(date_talon, time_talon)

    try:
        Talon.objects.get(doctor=doctor, date_of_receipt=date_of_receipt)

        data = {'error': 'Talon is already created'}
        return JsonResponse(data)
    except Talon.DoesNotExist:
        pass

    talon = Talon()
    talon.first_name = data.get('first-name')
    talon.last_name = data.get('last-name')
    talon.second_name = data.get('patronym')
    talon.address = address
    talon.doctor = doctor
    talon.date_of_receipt = date_of_receipt

    if birth_year and birth_month and birth_day:
        talon.birthday = datetime.date(year=int(birth_year),
                                       month=int(birth_month),
                                       day=int(birth_day))
    talon.phone = data.get('phone')
    talon.save()

    kwargs = {
        'pk': talon.id,
    }
    data = {
        'url': reverse('view-pdf', kwargs=kwargs),
    }
    return JsonResponse(data)
Пример #44
0
    def setUp(self):
        disconnect_signals()
        super().init_test_objects()
        self.monday_datetime = make_aware(parse_datetime("2019-11-25 00:00"))

        self.timeslot1 = Timeslot.objects.create(user=self.user1, name="Test")
        self.recurrence1 = TimeRecurrence.objects.create(
            timeslot=self.timeslot1,
            days={TimeRecurrence.Day.MONDAY},
            start=parse_time("00:30:00"),
            end=parse_time("00:30:01"),
        )
        self.recurrence2 = TimeRecurrence.objects.create(
            timeslot=self.timeslot1,
            days={TimeRecurrence.Day.MONDAY},
            start=parse_time("00:30:03"),
            end=parse_time("00:31"),
        )
        self.recurrence_all_day = TimeRecurrence.objects.create(
            timeslot=self.timeslot1,
            days={TimeRecurrence.Day.TUESDAY},
            start=TimeRecurrence.DAY_START,
            end=TimeRecurrence.DAY_END,
        )
Пример #45
0
def extract_fields(fields: Dict[str, Dict[str, Any]], params: QueryDict) -> Dict[str, Any]:
    kwargs = {}
    for _attr, _info in fields.items():
        if params.get(_attr):
            if _info['type'] == datetime.date:
                kwargs[_attr] = parse_date(params.get(_attr))
            elif _info['type'] == datetime.time:
                kwargs[_attr] = parse_time(params.get(_attr))
            elif _info['type'] == bool:
                kwargs[_attr] = bool(params.get(_attr, False))
            else:
                kwargs[_attr] = _info['type'](params.get(_attr))
        elif not params.get(_attr) and _info['required']:
            raise ApiException(reason="{} field is required".format(_attr))
    return kwargs
Пример #46
0
    def render(self, name, value, attrs=None, choices=()):
        if value:
            if type(value) == type("") or type(value) == type(u""):
                try:
                    value = parse_time(value)
                except ValueError:
                    value = None

            if value and isinstance(value, datetime.time):
                value_str = value.strftime("%H:%M:%S")
                if not value_str in self.choice_values:
                    choices = list(choices)
                    choices.append((value_str, value.strftime(self.repr_format)))
        return super(TimeChoiceWidget, self).render(name, value, attrs=attrs,
                                                    choices=choices)
Пример #47
0
def deserialize_instance(model, data):
    ret = model()
    for k, v in data.items():
        if v is not None:
            try:
                f = model._meta.get_field(k)
                if isinstance(f, DateTimeField):
                    v = dateparse.parse_datetime(v)
                elif isinstance(f, TimeField):
                    v = dateparse.parse_time(v)
                elif isinstance(f, DateField):
                    v = dateparse.parse_date(v)
            except FieldDoesNotExist:
                pass
        setattr(ret, k, v)
    return ret
Пример #48
0
def get_input(inFile):
    # Lê arquivo ignorando primeira e última linhas
    inFile = inFile.split('\n')[1:-1]
    
    #lista de entradas (ponto)
    person_list = []

    for line in inFile:
        splited_line = line.split("\t")
        splited_datetime = splited_line[4][:-1].split("  ")
        time = dateparse.parse_time(splited_datetime[1])
        date = datetime.strptime(splited_line[4][:-1], "%Y/%m/%d %H:%M").date()
        item = {"id": splited_line[2], "name": splited_line[3].strip(), "date": date, "time": time}
        person_list.append(item)

    for person in person_list:
        person_obj, created_person = Person.objects.get_or_create(id=person["id"], name=person["name"])
        date_obj, created_dates = Date.objects.get_or_create(date_fingerprint=person["date"])
        
        # criar uma linha para "pessoa"
        if (created_person):
            WorkedTime.objects.create(person=person_obj, date=date_obj, initial=person["time"]).save()

        # adicionar "time" no initial ou final
        else:
            # filtra última ocorrência da determinada pessoa
            last_workedtime = WorkedTime.objects.filter(person=person_obj).order_by('-date', '-initial')
            if (last_workedtime.exists()):
                # pega o objeto da pessoa filtrada
                last_workedtime = last_workedtime.latest('initial')
                # checa se deve atualizar o final
                if (not last_workedtime.final and person["date"] == last_workedtime.date.date_fingerprint and last_workedtime.initial < person["time"]):
                    last_workedtime.final = person["time"]
                    last_workedtime.save()
                # cria uma nova row preenchendo o initial
                elif (last_workedtime.final != person["time"]):
                    worked_obj, created_worked = WorkedTime.objects.get_or_create(person=person_obj, date=date_obj, initial=person["time"])
    
    # exclui os dados não pareados
    for person in person_list:
        person_obj = Person.objects.get(id=person["id"], name=person["name"])
        any_workedtime = WorkedTime.objects.filter(person=person_obj, final__isnull=True)            
        date_orphan = Date.objects.filter(worked_times=None)
        for each in any_workedtime:
            each.delete()
        for date in date_orphan:
            date.delete()
Пример #49
0
def copy_deliverable(db,deliverable_type, class_type):
    entries = select_homework(deliverable_type,db)
    for deliverable in entries:
        course = Course.objects.get(course_code=deliverable[0])
        date = parse_date(deliverable[2])
        if deliverable[3] is not None:
            time = parse_time(deliverable[3])
        else:
            time=None
        new_task = class_type(title=deliverable[1],
                                    due_date=date,
                                    time=time,
                                    course=course,
                                    type=deliverable_type
                                    )
        new_task.save()

    return
Пример #50
0
	def get_field_values(self):
		field_values = super(Record, self).get_field_values()
		
		min_time, max_time = time.max, time.min
		for card in self.fits_header.cards:
			try:
				card.verify('silentfix')
			except Exception, why:
				self.log.warning('Bad card in header %s: %s', card, why)
				continue
			if card.keyword.lower() == 'ut':
				try:
					ut = parse_time(card.value)
				except ValueError, why:
					self.log.warning('UT keyword has a ill formated value %s: %s', card.value, why)
				else:
					min_time = min(min_time, ut)
					max_time = max(max_time, ut)
Пример #51
0
    def convert_values(self, value, field):
        """SQLite returns floats when it should be returning decimals,
        and gets dates and datetimes wrong.
        For consistency with other backends, coerce when required.
        """
        internal_type = field.get_internal_type()
        if internal_type == 'DecimalField':
            return util.typecast_decimal(field.format_number(value))
        elif internal_type and internal_type.endswith('IntegerField') or internal_type == 'AutoField':
            return int(value)
        elif internal_type == 'DateField':
            return parse_date(value)
        elif internal_type == 'DateTimeField':
            return parse_datetime_with_timezone_support(value)
        elif internal_type == 'TimeField':
            return parse_time(value)

        # No field, or the field isn't known to be a decimal or integer
        return value
    def test_implicit_date_filters(self):
        john = Person.objects.get(name="John")
        # Mark was created at least one second after John.
        # mark = Person.objects.get(name="Mark")

        # Figure out what the date strings should look like based on the
        # serializer output.
        data = PersonSerializer(john).data

        date_str = JSONRenderer().render(data['date_joined']).decode('utf-8').strip('"')

        # Adjust for imprecise rendering of time
        datetime_str = JSONRenderer().render(parse_datetime(data['datetime_joined']) + datetime.timedelta(seconds=0.6)).decode('utf-8').strip('"')

        # Adjust for imprecise rendering of time
        dt = datetime.datetime.combine(datetime.date.today(), parse_time(data['time_joined'])) + datetime.timedelta(seconds=0.6)
        time_str = JSONRenderer().render(dt.time()).decode('utf-8').strip('"')

        # DateField
        GET = {
            'date_joined__lte': date_str,
        }
        f = AllLookupsPersonDateFilter(GET, queryset=Person.objects.all())
        self.assertEqual(len(list(f.qs)), 2)
        p = list(f.qs)[0]

        # DateTimeField
        GET = {
            'datetime_joined__lte': datetime_str,
        }
        f = AllLookupsPersonDateFilter(GET, queryset=Person.objects.all())
        self.assertEqual(len(list(f.qs)), 1)
        p = list(f.qs)[0]
        self.assertEqual(p.name, "John")

        # TimeField
        GET = {
            'time_joined__lte': time_str,
        }
        f = AllLookupsPersonDateFilter(GET, queryset=Person.objects.all())
        self.assertEqual(len(list(f.qs)), 1)
        p = list(f.qs)[0]
        self.assertEqual(p.name, "John")
Пример #53
0
def _time(val, default=None):
    if not val:
        val = ''
    
    # Handle the special case of '24:00'
    if val[:2] == '24':
        val = '23:59'

    ret = None
    try:
        ret = dateparse.parse_time(val)
    except ValueError as e:
        print_('Bad time string: {}'.format(val), file=sys.stderr)
        six.reraise(ValueError, e)

    if isinstance(ret, datetime.time):
        return ret
    if default is not None:
        return _time(default)
    return None
Пример #54
0
def unserialize_json(data, model_class):
    """ Take raw json data and unserialize to be compatible with a Django model """
    all_fields = model_class._meta.get_all_field_names()
    for field_name in data.keys():
        # skip if the model doesn't have that field
        if not (field_name in all_fields):
            continue
        # skip None
        if not data[field_name]:
            continue

        value = data[field_name]
        field_class = model_class._meta.get_field_by_name(field_name)[0]

        # decimal
        if issubclass(DecimalField, field_class.__class__):
            value = Decimal(value)

        # date
        elif issubclass(DateField, field_class.__class__):
            value = parse_date(data[field_name])
        # time
        elif issubclass(DateField, field_class.__class__):
            value = parse_time(data[field_name])
            # if not timezone aware default to SAST
            if not value.tzinfo:
                value = pytz.timezone("Africa/Johannesburg").localize(value)
        # datetime
        elif issubclass(DateTimeField, field_class.__class__):
            value = parse_datetime(data[field_name])
            # if not timezone aware default to SAST
            if not value.tzinfo:
                value = pytz.timezone("Africa/Johannesburg").localize(value)

        # foreign key - lookup based on uuid
        elif issubclass(ForeignKey, field_class.__class__):
            value = field_class.related.parent_model.objects.all_with_deleted().get(uuid=data[field_name])

        # done
        data[field_name] = value
    return data
Пример #55
0
    def to_python(self, value):
        if value is None:
            return None
        if isinstance(value, datetime.time):
            return value
        if isinstance(value, datetime.datetime):
            # Not usually a good idea to pass in a datetime here (it loses
            # information), but this can be a side-effect of interacting with a
            # database backend (e.g. Oracle), so we'll be accommodating.
            return value.time()

        try:
            parsed = parse_time(value)
            if parsed is not None:
                return parsed
        except ValueError:
            msg = self.error_messages['invalid_time'] % value
            raise exceptions.ValidationError(msg)

        msg = self.error_messages['invalid'] % value
        raise exceptions.ValidationError(msg)
Пример #56
0
def deserialize_instance(model, data={}):
    """
    Translate raw data into a model instance.
    This (and the whole session caching) is janky and should be re-thought.
    The spec offers an optional "state" param that could be used for this instead
    """
    ret = model()
    for k, v in data.items():
        if v is not None:
            try:
                f = model._meta.get_field(k)
                if isinstance(f, DateTimeField):
                    v = dateparse.parse_datetime(v)
                elif isinstance(f, TimeField):
                    v = dateparse.parse_time(v)
                elif isinstance(f, DateField):
                    v = dateparse.parse_date(v)
            except FieldDoesNotExist:
                pass
        setattr(ret, k, v)
    return ret
Пример #57
0
    def convert_values(self, value, field):
        """
        Coerce the value returned by the database backend into a consistent
        type that is compatible with the field type.

        In our case, cater for the fact that SQL Server < 2008 has no
        separate Date and Time data types.
        TODO: See how we'll handle this for SQL Server >= 2008
        """
        if value is None:
            return None
        if field and field.get_internal_type() == 'DateTimeField':
            if isinstance(value, string_types) and value:
                value = parse_datetime(value)
            return value
        elif field and field.get_internal_type() == 'DateField':
            if isinstance(value, datetime.datetime):
                value = value.date() # extract date
            elif isinstance(value, string_types):
                value = parse_date(value)
        elif field and field.get_internal_type() == 'TimeField':
            if (isinstance(value, datetime.datetime) and value.year == 1900 and value.month == value.day == 1):
                value = value.time() # extract time
            elif isinstance(value, string_types):
                # If the value is a string, parse it using parse_time.
                value = parse_time(value)
        # Some cases (for example when select_related() is used) aren't
        # caught by the DateField case above and date fields arrive from
        # the DB as datetime instances.
        # Implement a workaround stealing the idea from the Oracle
        # backend. It's not perfect so the same warning applies (i.e. if a
        # query results in valid date+time values with the time part set
        # to midnight, this workaround can surprise us by converting them
        # to the datetime.date Python type).
        elif isinstance(value, datetime.datetime) and value.hour == value.minute == value.second == value.microsecond == 0:
            value = value.date()
        # Force floats to the correct type
        elif value is not None and field and field.get_internal_type() == 'FloatField':
            value = float(value)
        return value