示例#1
0
文件: fields.py 项目: pjegouic/ban
 def coerce(self, value):
     if not value:
         value = [None, None]
     if isinstance(value, (list, tuple)):
         # '[)' means include lower bound but not upper.
         value = DateTimeTZRange(*value, bounds='[)')
     return value
示例#2
0
文件: views.py 项目: gis4dis/poster
def get_not_null_range(
    pt_range,
    observed_property,
    observation_provider_model,
    feature_of_interest,
    process
):

    obs_first = observation_provider_model.objects.filter(
        observed_property=observed_property,
        procedure=process,
        feature_of_interest=feature_of_interest,
        phenomenon_time_range__overlap=pt_range
    ).order_by('phenomenon_time_range')[:1]

    obs_latest = observation_provider_model.objects.filter(
        observed_property=observed_property,
        procedure=process,
        feature_of_interest=feature_of_interest,
        phenomenon_time_range__overlap=pt_range
    ).order_by('-phenomenon_time_range')[:1]

    if obs_first:
        return  DateTimeTZRange(
            obs_first[0].phenomenon_time_range.lower,
            obs_latest[0].phenomenon_time_range.upper
        )

    return None
示例#3
0
    def form(self):
        form = ListenerForm(self.request.GET)

        if form.is_valid():
            if form.cleaned_data['period']:
                self.period = form.cleaned_data['period']
            else:
                end = datetime.now().astimezone()
                start = end - timedelta(days=1)
                self.period = DateTimeTZRange(start, end)

            self.listeners = Listener.objects.filter(
                session__overlap=self.period)
            self.streams = 'stream__station__name'
            self.stream_order = '-stream'

            if form.cleaned_data['station']:
                self.listeners = self.listeners.filter(
                    stream__station=form.cleaned_data['station'])
                self.streams = 'stream__mountpoint'
                self.stream_order = 'stream'

            if form.cleaned_data['region']:
                countries = form.cleaned_data['region'].countries.values(
                    'country')
                self.listeners = self.listeners.filter(country__in=countries)

            if self.request.GET.getlist('referrer'):
                q = Q()
                for referrer in self.request.GET.getlist('referrer'):
                    q = q | Q(referer__contains=referrer)

                self.listeners = self.listeners.filter(q)

        return form
 def test_sets_date_range_from_date(self):
     Activity = self.apps.get_model('activities', 'Activity')
     activity = Activity.objects.get(pk=self.activity_id)
     self.assertIsNotNone(activity.date_range)
     self.assertEqual(
         activity.date_range, DateTimeTZRange(activity.date, activity.date + datetime.timedelta(minutes=30))
     )
示例#5
0
 def publish_date_filter(self, queryset, lower, upper):
     return queryset.filter(
         publish_date__overlap=DateTimeTZRange(
             lower=lower,
             upper=upper
         )
     )
示例#6
0
 def test_datetime_required(self):
     field = pg_forms.DateTimeRangeField(required=True)
     with self.assertRaises(exceptions.ValidationError) as cm:
         field.clean(['', ''])
     self.assertEqual(cm.exception.messages[0], 'This field is required.')
     value = field.clean(['2013-04-09 11:45', ''])
     self.assertEqual(value, DateTimeTZRange(datetime.datetime(2013, 4, 9, 11, 45), None))
示例#7
0
    def test_using_split_datetime_widget(self):
        class SplitDateTimeRangeField(pg_forms.DateTimeRangeField):
            base_field = forms.SplitDateTimeField

        class SplitForm(forms.Form):
            field = SplitDateTimeRangeField()

        form = SplitForm()
        self.assertHTMLEqual(str(form), '''
            <tr>
                <th>
                <label for="id_field_0">Field:</label>
                </th>
                <td>
                    <input id="id_field_0_0" name="field_0_0" type="text" />
                    <input id="id_field_0_1" name="field_0_1" type="text" />
                    <input id="id_field_1_0" name="field_1_0" type="text" />
                    <input id="id_field_1_1" name="field_1_1" type="text" />
                </td>
            </tr>
        ''')
        form = SplitForm({
            'field_0_0': '01/01/2014',
            'field_0_1': '00:00:00',
            'field_1_0': '02/02/2014',
            'field_1_1': '12:12:12',
        })
        self.assertTrue(form.is_valid())
        lower = datetime.datetime(2014, 1, 1, 0, 0, 0)
        upper = datetime.datetime(2014, 2, 2, 12, 12, 12)
        self.assertEqual(form.cleaned_data['field'], DateTimeTZRange(lower, upper))
示例#8
0
 def test_loading(self):
     instance = list(serializers.deserialize('json', self.test_data))[0].object
     self.assertEqual(instance.ints, NumericRange(0, 10))
     self.assertEqual(instance.floats, NumericRange(empty=True))
     self.assertEqual(instance.bigints, None)
     self.assertEqual(instance.dates, DateRange(self.lower_date, self.upper_date))
     self.assertEqual(instance.timestamps, DateTimeTZRange(self.lower_dt, self.upper_dt))
示例#9
0
 def search__at(self, op, value): # pylint: disable=unused-argument
     min_value, max_value = value_parsers.parse_date(value)
     date_range = DateTimeTZRange(min_value, max_value, '[]')
     returned = self.MODEL.timespan.overlaps(date_range)
     if self.MODEL is Test:
         returned &= Session.query.filter(Session.id == Test.session_id).filter(Session.timespan.overlaps(date_range)).exists().correlate(Test)
     return returned
示例#10
0
def gen_datetime_range():
    from psycopg2.extras import DateTimeTZRange

    base_datetime = gen_datetime()
    interval = gen_interval()
    args = sorted([base_datetime - interval, base_datetime + interval])
    return DateTimeTZRange(*args)
 def create_users(self):
     su_name = os.getenv("SUPERUSER_NAME")
     su_password = os.getenv("SUPERUSER_PASSWORD")
     if su_name:
         User.objects.create_superuser(su_name, su_name, su_password)
     sub_name = os.getenv("SUBSCRIBER_NAME")
     sub_password = os.getenv("SUBSCRIBER_PASSWORD")
     if sub_name:
         account = Account.objects.create()
         market = {
             "code": "DFW",
             "name": "Dallas",
             "type": "city",
             "country": {
                 "code": "US"
             },
             "subdivision": {
                 "name": "Texas"
             },
         }
         u = User.objects.create_user(sub_name,
                                      sub_name,
                                      sub_password,
                                      account=account,
                                      market=market)
         Subscriptions.objects.create(
             account=u.account,
             plan="basic-plus",
             period=DateTimeTZRange(now(),
                                    now() + timedelta(days=365)),
         )
示例#12
0
    def form_valid(self, form):
        team = Team.objects.get(camp=self.camp, slug=self.kwargs["team_slug"])
        current_timezone = timezone.get_current_timezone()

        start_datetime = form.cleaned_data["from_datetime"].astimezone(
            current_timezone)
        number_of_shifts = form.cleaned_data["number_of_shifts"]
        shift_length = form.cleaned_data["shift_length"]
        people_required = form.cleaned_data["people_required"]

        shifts = []
        for index in range(number_of_shifts):
            shift_range = DateTimeTZRange(
                start_datetime,
                start_datetime + timezone.timedelta(minutes=shift_length),
            )
            shifts.append(
                TeamShift(team=team,
                          people_required=people_required,
                          shift_range=shift_range))
            start_datetime += timezone.timedelta(minutes=shift_length)

        TeamShift.objects.bulk_create(shifts)

        return super().form_valid(form)
示例#13
0
def slug_date_to_range(raw_date_string):
    """Parse slug's date ('yymmdd' or 'yy--dd') to Date object."""
    is_single_day = True

    raw_month = raw_date_string[0:2]
    raw_day = raw_date_string[2:4]
    raw_year = raw_date_string[4:6]

    if raw_day == '--':
        raw_day = '01'
        is_single_day = False

    first_day = timezone.make_aware(
        datetime.strptime(
            '20{}-{}-{}'.format(raw_year, raw_month, raw_day),
            '%Y-%m-%d'
        )
    )

    delta = relativedelta(days=+1)
    if not is_single_day:
        delta = relativedelta(months=+1)

    return DateTimeTZRange(
        lower=first_day,
        upper=(first_day + delta)
    )
示例#14
0
    def test_using_split_datetime_widget(self):
        class SplitDateTimeRangeField(pg_forms.DateTimeRangeField):
            base_field = forms.SplitDateTimeField

        class SplitForm(forms.Form):
            field = SplitDateTimeRangeField()

        form = SplitForm()
        self.assertHTMLEqual(
            str(form),
            """
            <tr>
                <th>
                <label>Field:</label>
                </th>
                <td>
                    <input id="id_field_0_0" name="field_0_0" type="text">
                    <input id="id_field_0_1" name="field_0_1" type="text">
                    <input id="id_field_1_0" name="field_1_0" type="text">
                    <input id="id_field_1_1" name="field_1_1" type="text">
                </td>
            </tr>
        """,
        )
        form = SplitForm({
            "field_0_0": "01/01/2014",
            "field_0_1": "00:00:00",
            "field_1_0": "02/02/2014",
            "field_1_1": "12:12:12",
        })
        self.assertTrue(form.is_valid())
        lower = datetime.datetime(2014, 1, 1, 0, 0, 0)
        upper = datetime.datetime(2014, 2, 2, 12, 12, 12)
        self.assertEqual(form.cleaned_data["field"],
                         DateTimeTZRange(lower, upper))
示例#15
0
    def test_write_tstzrange(self):
        test_value = DateTimeTZRange(
            datetime.datetime(2014,
                              6,
                              8,
                              12,
                              12,
                              45,
                              tzinfo=psycopg2.tz.FixedOffsetTimezone(
                                  offset=720, name=None)),
            datetime.datetime(2016,
                              7,
                              6,
                              14,
                              12,
                              8,
                              tzinfo=psycopg2.tz.FixedOffsetTimezone(
                                  offset=720, name=None)))
        test_columns_info = []
        col = DbColumn()
        col.data_type = datatypes.DATATYPE_TSTZRANGE
        col.provider = PG_PROVIDER_NAME
        test_columns_info.append(col)
        mock_storage_data_reader = MockStorageDataReader(
            self._cursor, test_columns_info)
        mock_storage_data_reader.get_value = mock.MagicMock(
            return_value=test_value)

        res = self._writer.write_row(mock_storage_data_reader)
        self.assertEqual(
            self.get_expected_length_with_additional_buffer_for_size(
                len("[2014-06-08T12:12:45+12:00,2016-07-06T14:12:08+12:00)")),
            res)
示例#16
0
def import_number_of_events(day_from, day_to):
    if type(day_from) is date and type(day_to) is date:
        day_from = datetime.combine(day_from, datetime.min.time())
        day_to = datetime.combine(day_to, datetime.min.time())
        day_from = day_from.replace(tzinfo=UTC_P0100)
        day_to = day_to.replace(tzinfo=UTC_P0100)

    whole_extent = EventExtent.objects.get(name_id="brno_brno_venkov_d1")
    whole_extent_units = whole_extent.admin_units.all()

    custom_categories = CategoryCustomGroup.objects.all()

    # get_or_create_props()
    observed_property = Property.objects.get(
        name_id="number_of_emerged_events")
    procedure = Process.objects.get(name_id="observation")

    time_from = day_from
    time_to = time_from + timedelta(hours=1)
    dt_range = DateTimeTZRange(time_from, time_to)

    while (time_to <= day_to):
        for category in custom_categories:
            for admin_unit in whole_extent_units:
                admin_geom = admin_unit.geometry

                number_events = NumberOfEventsObservation.objects.update_or_create(
                    phenomenon_time_range=dt_range,
                    observed_property=observed_property,
                    feature_of_interest=admin_unit,
                    procedure=procedure,
                    category_custom_group=category,
                )[0]

                events = EventObservation.objects.filter(
                    phenomenon_time_range__startswith__range=(time_from,
                                                              time_to),
                    point_geometry__intersects=admin_geom,
                    category__custom_group=category)

                number_events.result = len(events)
                number_events.save()

        print('Time {} {}'.format(time_from, time_to))
        time_from = time_from + timedelta(hours=1)
        time_to = time_to + timedelta(hours=1)
        dt_range = DateTimeTZRange(time_from, time_to)
示例#17
0
    def _set_duration_for_user(self, user_info, is_scheduling=True):
        localized_start = self._localize(self.utc_duration.lower,
                                         user_info.local_tz)

        localized_end = self._localize(self.utc_duration.upper,
                                       user_info.local_tz)

        if is_scheduling:
            self.scheduling_tz_duration = DateTimeTZRange(
                localized_start,
                localized_end,
            )
        else:
            self.scheduled_tz_duration = DateTimeTZRange(
                localized_start,
                localized_end,
            )
 def test_sets_date_range_from_date(self):
     PickupDate = self.apps.get_model('pickups', 'PickupDate')
     pickup = PickupDate.objects.get(pk=self.pickup_id)
     self.assertIsNotNone(pickup.date_range)
     self.assertEqual(
         pickup.date_range,
         DateTimeTZRange(pickup.date,
                         pickup.date + datetime.timedelta(minutes=30)))
示例#19
0
 def test_datetime_prepare_value(self):
     field = pg_forms.DateTimeRangeField()
     value = field.prepare_value(
         DateTimeTZRange(
             datetime.datetime(2015, 5, 22, 16, 6, 33, tzinfo=timezone.utc),
             None))
     self.assertEqual(value,
                      [datetime.datetime(2015, 5, 22, 18, 6, 33), None])
示例#20
0
    def get_days(self, camppart):
        """
        Returns a list of DateTimeTZRanges representing the days during the specified part of the camp.
        """
        if not hasattr(self, camppart):
            logger.error("nonexistant field/attribute")
            return False

        field = getattr(self, camppart)

        if (
            not hasattr(field, "__class__")
            or not hasattr(field.__class__, "__name__")
            or not field.__class__.__name__ == "DateTimeTZRange"
        ):
            logger.error("this attribute is not a datetimetzrange field: %s" % field)
            return False

        daycount = (field.upper - field.lower).days
        days = []
        for i in range(0, daycount):
            if i == 0:
                # on the first day use actual start time instead of midnight
                days.append(
                    DateTimeTZRange(
                        field.lower,
                        (field.lower + timedelta(days=i + 1)).replace(hour=0),
                    )
                )
            elif i == daycount - 1:
                # on the last day use actual end time instead of midnight
                days.append(
                    DateTimeTZRange(
                        (field.lower + timedelta(days=i)).replace(hour=0),
                        field.lower + timedelta(days=i + 1),
                    )
                )
            else:
                # neither first nor last day, goes from midnight to midnight
                days.append(
                    DateTimeTZRange(
                        (field.lower + timedelta(days=i)).replace(hour=0),
                        (field.lower + timedelta(days=i + 1)).replace(hour=0),
                    )
                )
        return days
示例#21
0
文件: models.py 项目: lpagac/sharebnb
    def is_available(self, start, end):
        """ filter out dates before timezone.now
            check if start,end overlaps with any booking for listing
            return Boolean
        """

        overlap_bookings = self.booking_set.filter(
            date_time_range__overlap=DateTimeTZRange(start, end))
        return len(overlap_bookings) == 0
示例#22
0
 def test_product_not_available_by_time(self):
     """ The product is not available if now is outside the timeframe. """
     available_in = DateTimeTZRange(
         lower=timezone.now() - timezone.timedelta(5),
         upper=timezone.now() - timezone.timedelta(1))
     product = ProductFactory(available_in=available_in)
     # The factory defines the timeframe as now and 31 days forward.
     self.assertFalse(product.is_time_available)
     self.assertFalse(product.is_available())
示例#23
0
    def get_queryset(self):
        queryset = self.queryset
        start = self.request.query_params.get('start', None)
        end = self.request.query_params.get('end', None)
        if start is not None and end is not None:
            queryset = queryset.filter(
                during__contained_by=DateTimeTZRange(start, end))

        return queryset
示例#24
0
 def test_range_object_boundaries_range_with_default_bounds(self):
     range_ = DateTimeTZRange(
         timezone.now(),
         timezone.now() + datetime.timedelta(hours=1),
         bounds="()",
     )
     RangesModel.objects.create(timestamps_closed_bounds=range_)
     loaded = RangesModel.objects.get()
     self.assertEqual(loaded.timestamps_closed_bounds, range_)
示例#25
0
文件: db.py 项目: carlbordum/mox
def list_objects(class_name, uuid, virkning_fra, virkning_til, registreret_fra,
                 registreret_til):
    """List objects with the given uuids, optionally filtering by the given
    virkning and registering periods."""

    assert isinstance(uuid, list) or not uuid

    sql_template = jinja_env.get_template('list_objects.sql')

    sql_restrictions = get_restrictions_as_sql(get_authenticated_user(),
                                               class_name, Operation.READ)

    sql = sql_template.render(class_name=class_name,
                              restrictions=sql_restrictions)

    registration_period = None
    if registreret_fra is not None or registreret_til is not None:
        registration_period = DateTimeTZRange(registreret_fra, registreret_til)

    conn = get_connection()
    cursor = conn.cursor()
    try:
        cursor.execute(
            sql, {
                'uuid': uuid,
                'registrering_tstzrange': registration_period,
                'virkning_tstzrange': DateTimeTZRange(virkning_fra,
                                                      virkning_til)
            })
    except psycopg2.Error as e:
        if e.pgcode[:2] == 'MO':
            status_code = int(e.pgcode[2:])
            raise DBException(status_code, e.pgerror)
        else:
            raise

    output = cursor.fetchone()
    if not output:
        # nothing found
        raise NotFoundException("{0} with UUID {1} not found.".format(
            class_name, uuid))
    # import json
    # print json.dumps(output, indent=2)
    return filter_json_output(output)
示例#26
0
    def save(self, *args, **kwargs):
        self.duration = DateTimeTZRange(self.begin, self.end, '[)')

        if not self.access_code:
            access_code_type = self.resource.access_code_type
            if self.resource.is_access_code_enabled(
            ) and self.resource.generate_access_codes:
                self.access_code = generate_access_code(access_code_type)

        return super().save(*args, **kwargs)
示例#27
0
 def test_product_is_available_from_now_on(self):
     """ The product is available because we are after lower bound. """
     available_in = DateTimeTZRange(lower=timezone.now() -
                                    timezone.timedelta(1))
     product = ProductFactory(available_in=available_in)
     # Make sure there is no upper - just in case.
     self.assertEqual(product.available_in.upper, None)
     # The factory defines the timeframe as now and 31 days forward.
     self.assertTrue(product.is_time_available)
     self.assertTrue(product.is_available())
示例#28
0
    def test_multiple_day_range(self):
        """Verify 'budget.utils.slug_date_to_range' multi-day behavior.

        The method should turn a multiple-day formatted slug date
        '05--15') into a week/month date range.

        The resulting range should also have correct time zones.
        """
        # 28-day month
        feb_slug_date = '02--15'
        feb_actual_range = slug_date_to_range(feb_slug_date)

        feb_intended_range = DateTimeTZRange(
            lower=make_aware(datetime(2015, 2, 1)),
            upper=make_aware(datetime(2015, 3, 1)))
        self.assertEqual(feb_intended_range, feb_actual_range)

        # 29-day month
        leap_slug_date = '02--16'
        leap_actual_range = slug_date_to_range(leap_slug_date)

        leap_intended_range = DateTimeTZRange(
            lower=make_aware(datetime(2016, 2, 1)),
            upper=make_aware(datetime(2016, 3, 1)))
        self.assertEqual(leap_intended_range, leap_actual_range)

        # 30-day month
        sept_slug_date = '09--15'
        sept_actual_range = slug_date_to_range(sept_slug_date)

        sept_intended_range = DateTimeTZRange(
            lower=make_aware(datetime(2015, 9, 1)),
            upper=make_aware(datetime(2015, 10, 1)))
        self.assertEqual(sept_intended_range, sept_actual_range)

        # 31-day month
        oct_slug_date = '10--15'
        oct_actual_range = slug_date_to_range(oct_slug_date)

        oct_intended_range = DateTimeTZRange(
            lower=make_aware(datetime(2015, 10, 1)),
            upper=make_aware(datetime(2015, 11, 1)))
        self.assertEqual(oct_intended_range, oct_actual_range)
示例#29
0
 def save(self, *args, **kwargs):
     # Staff are automatically confirmed.
     if self.reserved_by.groups.filter(name='staff').exists():
         self.is_confirmed = True
         self.confirmed_by = self.reserved_by
     # Take the start and end dates to generate a timerange
     # to actually query on as solves issues just using start
     # and end dates.
     self.reservation = DateTimeTZRange(self.start, self.end)
     super(EquipmentReservation, self).save(*args, **kwargs)
示例#30
0
 def test_datetime_range(self):
     objs = [
         RangeLookupsModel.objects.create(timestamp='2015-01-01T09:00:00'),
         RangeLookupsModel.objects.create(timestamp='2015-05-05T17:00:00'),
     ]
     self.assertSequenceEqual(
         RangeLookupsModel.objects.filter(
             timestamp__contained_by=DateTimeTZRange(
                 '2015-01-01T09:00', '2015-05-04T23:55')),
         [objs[0]],
     )