django.utils.timezone.make_aware

Here are the examples of the python api django.utils.timezone.make_aware taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: pretix
Source File: test_orders.py
View license
@pytest.mark.django_db
def test_expiry_weekdays(event):
    today = make_aware(datetime(2016, 9, 20, 15, 0, 0, 0))
    event.settings.set('payment_term_days', 5)
    event.settings.set('payment_term_weekdays', True)
    order = _create_order(event, email='[email protected]', positions=[],
                          now_dt=today, payment_provider=FreeOrderProvider(event),
                          locale='de')
    assert (order.expires - today).days == 6
    assert order.expires.weekday() == 0

    today = make_aware(datetime(2016, 9, 19, 15, 0, 0, 0))
    order = _create_order(event, email='[email protected]', positions=[],
                          now_dt=today, payment_provider=FreeOrderProvider(event),
                          locale='de')
    assert (order.expires - today).days == 7
    assert order.expires.weekday() == 0

Example 2

View license
def add_default_times(apps, schema_editor):
    Time = apps.get_model('events', 'Time')
    db_alias = schema_editor.connection.alias
    Time.objects.using(db_alias).bulk_create([
        Time(value=make_aware(datetime.datetime.combine(
            datetime.date(*date_args), datetime.time(*time_args),
        )))
        for date_args, time_args_list in DEFAULT_TIME_ARGS.items()
        for time_args in time_args_list
    ])

Example 3

View license
def remove_default_times(apps, schema_editor):
    Time = apps.get_model('events', 'Time')
    db_alias = schema_editor.connection.alias
    values = [
        make_aware(datetime.datetime.combine(
            datetime.date(*date_args), datetime.time(*time_args),
        ))
        for date_args, time_args_list in DEFAULT_TIME_ARGS.items()
        for time_args in time_args_list
    ]
    Time.objects.using(db_alias).filter(value__in=values).delete()

Example 4

Project: pythondotorg
Source File: utils.py
View license
def convert_dt_to_aware(dt):
    if not isinstance(dt, datetime.datetime):
        dt = date_to_datetime(dt)
    if not is_aware(dt):
        # we don't want to use get_current_timezone() because
        # settings.TIME_ZONE may be set something different than
        # UTC in the future
        return make_aware(dt, timezone=pytz.UTC)
    return dt

Example 5

Project: chain-api
Source File: tests.py
View license
    def test_sensor_data_should_be_postable(self):
        device = self.get_a_device()
        sensor = self.get_a_sensor()
        sensor_data = self.get_resource(
            sensor.links['ch:dataHistory'].href)
        data_url = sensor_data.links.createForm.href
        timestamp = make_aware(datetime(2013, 1, 1, 0, 0, 0), utc)
        data = {
            'value': 23,
            'timestamp': timestamp.isoformat()
        }
        self.create_resource(data_url, data)
        db_data = ScalarData.objects.get(
            sensor__metric__name=sensor.metric,
            sensor__device__name=device.name,
            timestamp=timestamp)
        self.assertEqual(db_data.value, data['value'])

Example 6

Project: folivora
Source File: models.py
View license
    def sync_versions(self):
        if self.initial_sync_done:
            return
        client = CheeseShop()
        versions = client.get_package_versions(self.name)
        for version in versions:
            urls = client.get_release_urls(self.name, version)
            if urls:
                url = urls[0]
                utime = time.mktime(url['upload_time'].timetuple())
                release_date = make_aware(
                    datetime.datetime.fromtimestamp(utime),
                    pytz.UTC)
                PackageVersion.objects.get_or_create(
                    package=self,
                    version=version,
                    release_date=release_date)
        self.initial_sync_done = True
        self.save()

Example 7

Project: folivora
Source File: tests.py
View license
    def test_creation(self):
        Package.objects.create(name='gunicorn',
                               url='http://pypi.python.org/pypi/gunicorn',
                               provider='pypi')
        pkg = Package.objects.get(name='gunicorn')
        dt = make_aware(datetime(2012, 7, 26, 23, 51, 18), pytz.UTC)
        PackageVersion.objects.create(package=pkg,
                                      version='0.14.6',
                                      release_date=dt)
        vers = PackageVersion.objects.get(package__name='gunicorn',
                                          version='0.14.6')
        self.assertEqual(vers.package, pkg)
        self.assertEqual(vers.version, '0.14.6')
        self.assertEqual(vers.release_date, dt)

Example 8

Project: folivora
Source File: tests.py
View license
    @mock.patch('folivora.tasks.CheeseShop', CheesyMock)
    @mock.patch('folivora.models.Package.sync_versions', stub)
    def test_package_removal_sync_delete_versions(self):
        pkg = Package.create_with_provider_url('gunicorn-del')
        dt = make_aware(datetime(2012, 7, 26, 23, 51, 18), pytz.UTC)
        pkg.versions.add(PackageVersion(version='0.14.6', release_date=dt))
        result = tasks.sync_with_changelog.apply(throw=True)
        self.assertTrue(result.successful())

        # Check that the log as created
        qs = Log.objects.filter(project=self.project, action='remove_package')
        self.assertEqual(qs.count(), 1)

        pkg = Package.objects.get(name='gunicorn-del')
        self.assertEqual(pkg.versions.count(), 0)

Example 9

Project: folivora
Source File: tests.py
View license
    @mock.patch('folivora.tasks.CheeseShop', CheesyMock)
    @mock.patch('folivora.models.Package.sync_versions', stub)
    def test_package_removal_sync_delete_versions_preserve_dependencies(self):
        pkg = Package.create_with_provider_url('gunicorn-del')
        dt = make_aware(datetime(2012, 7, 26, 23, 51, 18), pytz.UTC)
        version = PackageVersion(version='0.14.6', release_date=dt)
        pkg.versions.add(version)
        dep = ProjectDependency.objects.create(
            project=self.project,
            package=pkg,
            version='0.14.6',
            update=version)
        result = tasks.sync_with_changelog.apply(throw=True)
        self.assertTrue(result.successful())

        pkg = Package.objects.get(name='gunicorn-del')
        expected = pkg.projectdependency_set.get(version='0.14.6')
        self.assertEqual(expected, dep)
        self.assertEqual(expected.update, None)

Example 10

View license
    def convert_value(self, value, expression, connection, context):
        if settings.USE_TZ:
            if value is None:
                raise ValueError(
                    "Database returned an invalid value in QuerySet.datetimes(). "
                    "Are time zone definitions for your database and pytz installed?"
                )
            value = value.replace(tzinfo=None)
            value = timezone.make_aware(value, self.tzinfo)
        return value

Example 11

Project: django-scaffolding
Source File: tubes.py
View license
    def next(self):
        delta = (self.enddate - self.startdate).days
        moment = self.startdate + datetime.timedelta(random.randint(0, delta))
        if self.timezone:
            moment = make_aware(moment, self.timezone)
        return moment

Example 12

Project: discord-bot
Source File: plugin.py
View license
    def on_message_edit(self, before, after):
        yield from super().on_message_edit(before, after)

        logged_message = LoggedMessage.objects.filter(discord_id=before.id).first()
        if not logged_message:
            return

        logged_message.edited_timestamp = make_aware(after.edited_timestamp, utc)
        logged_message.content = after.content
        logged_message.num_lines = len(after.content.splitlines())
        logged_message.save()

Example 13

Project: drum
Source File: poll_rss.py
View license
    def entry_to_link_dict(self, entry):
        link = {
            "title": entry.title,
            "link": self.link_from_entry(entry),
            "gen_description": False,
        }
        try:
            publish_date = entry.published_parsed
        except AttributeError:
            pass
        else:
            publish_date = datetime.fromtimestamp(mktime(publish_date))
            publish_date = make_aware(publish_date, get_default_timezone())
            link["publish_date"] = publish_date
        return link

Example 14

Project: ion
Source File: date.py
View license
def get_date_range_this_year(now=None):
    """Return the starting and ending date of the current school year."""
    if now is None:
        now = datetime.datetime.now().date()
    if now.month <= settings.YEAR_TURNOVER_MONTH:
        date_start = datetime.datetime(now.year - 1, 9, 1)
        date_end = datetime.datetime(now.year, 7, 1)
    else:
        date_start = datetime.datetime(now.year, 9, 1)
        date_end = datetime.datetime(now.year + 1, 7, 1)
    return timezone.make_aware(date_start), timezone.make_aware(date_end)

Example 15

Project: pootle
Source File: timezone.py
View license
def test_make_naive_default_tz(settings):
    """Tests datetimes are made naive of the configured timezone."""
    settings.USE_TZ = True

    datetime_object = timezone.make_aware(datetime(2016, 1, 2, 21, 52, 25),
                                          timezone=pytz.timezone('Europe/Helsinki'))
    assert timezone.is_aware(datetime_object)
    naive_datetime = make_naive(datetime_object)
    assert timezone.is_naive(naive_datetime)

    # Conversion from a Helsinki aware datetime to a naive datetime in Amsterdam
    # should decrement 1 hour (UTC+2 vs. UTC+1)
    assert naive_datetime.hour == (datetime_object.hour - 1) % 24

Example 16

Project: pootle
Source File: timezone.py
View license
def test_make_naive_explicit_tz(settings):
    """Tests datetimes are made naive of the given timezone."""
    settings.USE_TZ = True

    datetime_object = timezone.make_aware(datetime(2016, 1, 2, 21, 52, 25),
                                          timezone=pytz.timezone('Europe/Helsinki'))
    assert timezone.is_aware(datetime_object)
    naive_datetime = make_naive(datetime_object, tz=pytz.timezone('Asia/Bangkok'))
    assert timezone.is_naive(naive_datetime)

    # Conversion from a Helsinki aware datetime to a naive datetime in Bangkok
    # should increment 5 hours (UTC+2 vs. UTC+7)
    assert naive_datetime.hour == (datetime_object.hour + 5) % 24

Example 17

Project: django-happenings
Source File: managers.py
View license
    @staticmethod
    def get_first_and_last(year, month):
        """Returns two datetimes: first day and last day of given year&month"""
        ym_first = make_aware(
            datetime.datetime(year, month, 1),
            get_default_timezone()
        )
        ym_last = make_aware(
            datetime.datetime(year, month, monthrange(year, month)[1], 23, 59, 59, 1000000-1),
            get_default_timezone()
        )
        return ym_first, ym_last

Example 18

View license
    def test_monthly_with_end_repeat(self):
        event = create_event(
            start_date=(2014, 3, 31),
            end_date=(2014, 3, 31),
            created_by=self.user,
            title="Mondo",
            description="Testing 1 2 3",
            repeat="MONTHLY",
            end_repeat=date(2014, 5, 31),
            utc=True
        )
        d = make_aware(datetime(2014, 3, 3), utc)
        fin = d + timedelta(days=365)
        events = self.upcoming_events(event, d, fin)
        self.assertEqual(len(events), 2)

Example 19

View license
    def test_monthly_future_event(self):
        event = create_event(
            start_date=(2015, 3, 10),
            end_date=(2015, 3, 10),
            created_by=self.user,
            title="Veronika",
            description="Testing 1 2 3",
            repeat="MONTHLY",
            utc=True
        )
        d = make_aware(datetime(2015, 1, 6), utc)
        fin = d + timedelta(days=365)
        events = self.upcoming_events(event, d, fin)
        self.assertEqual(len(events), 5)
        self.assertEqual(events[0][0].date(), date(2015, 3, 10))

Example 20

View license
    def test_weekly(self):
        event = create_event(
            start_date=(2014, 3, 1),
            end_date=(2014, 3, 3),
            created_by=self.user,
            title="Veronika",
            description="Testing 1 2 3",
            repeat="WEEKLY",
            utc=True
        )
        d = make_aware(datetime(2014, 3, 6), utc)
        fin = d + timedelta(days=90)
        events = self.upcoming_events(event, d, fin)
        self.assertEqual(len(events), 5)
        for i in range(5):
            self.assertEqual(events[i][1].title, event.title)
            self.assertEqual(events[i][1].start_date, event.start_date)
        self.assertEqual(events[0][0].date(), date(2014, 3, 8))
        self.assertEqual(events[1][0].date(), date(2014, 3, 15))

Example 21

View license
    def test_weekly_future_event(self):
        event = create_event(
            start_date=(2014, 3, 1),
            end_date=(2014, 3, 3),
            created_by=self.user,
            title="Veronika",
            description="Testing 1 2 3",
            repeat="WEEKLY",
            utc=True
        )
        d = make_aware(datetime(2013, 12, 1), utc)
        fin = d + timedelta(days=900)
        events = self.upcoming_events(event, d, fin)
        self.assertEqual(len(events), 5)
        self.assertEqual(events[0][0].date(), date(2014, 3, 1))
        self.assertEqual(events[1][0].date(), date(2014, 3, 8))
        self.assertEqual(events[2][0].date(), date(2014, 3, 15))

Example 22

View license
    def test_biweekly(self):
        event = create_event(
            start_date=(2014, 3, 1),
            end_date=(2014, 3, 3),
            created_by=self.user,
            title="Veronika",
            description="Testing 1 2 3",
            repeat="BIWEEKLY",
            utc=True
        )
        d = make_aware(datetime(2014, 5, 8), utc)
        fin = d + timedelta(days=90)
        events = self.upcoming_events(event, d, fin)
        self.assertEqual(len(events), 5)
        for i in range(5):
            self.assertEqual(events[i][1].title, event.title)
            self.assertEqual(events[i][1].start_date, event.start_date)
        self.assertEqual(events[0][0].date(), date(2014, 5, 10))
        self.assertEqual(events[1][0].date(), date(2014, 5, 24))

Example 23

View license
    def test_daily(self):
        event = create_event(
            start_date=(2014, 3, 1),
            end_date=(2014, 3, 1),
            created_by=self.user,
            title="Veronika",
            description="Testing 1 2 3",
            repeat="DAILY",
            utc=True
        )
        d = make_aware(datetime(2014, 5, 6), utc)
        fin = d + timedelta(days=90)
        events = self.upcoming_events(event, d, fin)
        self.assertEqual(len(events), 5)
        for i in range(5):
            self.assertEqual(events[i][1].title, event.title)
            self.assertEqual(events[i][1].start_date, event.start_date)
        self.assertEqual(events[0][0].date(), date(2014, 5, 6))
        self.assertEqual(events[1][0].date(), date(2014, 5, 7))

Example 24

View license
    def test_daily_future_event(self):
        event = create_event(
            start_date=(2014, 3, 1),
            end_date=(2014, 3, 1),
            created_by=self.user,
            title="Veronika",
            description="Testing 1 2 3",
            repeat="DAILY",
            utc=True
        )
        d = make_aware(datetime(2013, 11, 6), utc)
        fin = d + timedelta(days=900)
        events = self.upcoming_events(event, d, fin)
        self.assertEqual(len(events), 5)
        self.assertEqual(events[0][0].date(), date(2014, 3, 1))
        self.assertEqual(events[1][0].date(), date(2014, 3, 2))

Example 25

View license
    def test_weekday_start_on_weekend(self):
        event = create_event(
            start_date=(2014, 3, 1),
            end_date=(2014, 3, 1),
            created_by=self.user,
            title="Veronika",
            description="Testing 1 2 3",
            repeat="WEEKDAY",
            utc=True
        )
        d = make_aware(datetime(2014, 5, 3), utc)
        fin = d + timedelta(days=90)
        events = self.upcoming_events(event, d, fin)
        self.assertEqual(len(events), 5)
        for i in range(5):
            self.assertEqual(events[i][1].title, event.title)
            self.assertEqual(events[i][1].start_date, event.start_date)
        self.assertEqual(events[0][0].date(), date(2014, 5, 5))
        self.assertEqual(events[1][0].date(), date(2014, 5, 6))

Example 26

View license
    def test_weekday_with_end_repeat(self):
        event = create_event(
            start_date=(2014, 3, 31),
            end_date=(2014, 3, 31),
            created_by=self.user,
            title="Groove",
            description="Testing 1 2 3",
            repeat="WEEKDAY",
            end_repeat=date(2014, 4, 1),
            utc=True
        )
        d = make_aware(datetime(2014, 3, 3), utc)
        fin = d + timedelta(days=365)
        events = self.upcoming_events(event, d, fin)
        self.assertEqual(len(events), 2)

Example 27

View license
    def test_weekday_event_in_future(self):
        event = create_event(
            start_date=(2014, 3, 10),
            end_date=(2014, 3, 10),
            created_by=self.user,
            title="Veronika",
            description="Testing 1 2 3",
            repeat="WEEKDAY",
            utc=True
        )
        d = make_aware(datetime(2014, 2, 7), utc)
        fin = d + timedelta(days=90)
        events = self.upcoming_events(event, d, fin)
        self.assertEqual(len(events), 5)
        for i in range(5):
            self.assertEqual(events[i][1].title, event.title)
            self.assertEqual(events[i][1].start_date, event.start_date)
        self.assertEqual(events[0][0].date(), date(2014, 3, 10))

Example 28

View license
    def test_single_day_event_in_future(self):
        event = create_event(
            start_date=(2014, 3, 7),
            end_date=(2014, 3, 7),
            created_by=self.user,
            title="Vera",
            description="Testing 1 2 3",
            utc=True
        )
        d = make_aware(datetime(2014, 3, 3), utc)
        fin = d + timedelta(days=90)
        events = self.upcoming_events(event, d, fin)
        self.assertEqual(len(events), 1)
        self.assertEqual(events[0][0], event.start_date)
        self.assertEqual(events[0][1].title, event.title)
        self.assertEqual(events[0][1].start_date, event.start_date)

Example 29

View license
    def test_event_in_past(self):
        """
        Sending an event that has already started and ended, and that
        doesn't have an end repeat, should return an empty list.
        """
        event = create_event(
            start_date=(2014, 3, 7),
            end_date=(2014, 3, 7),
            created_by=self.user,
            title="Elvira",
            description="Testing 1 2 3",
            utc=True
        )
        d = make_aware(datetime(2015, 3, 4), utc)
        fin = d + timedelta(days=90)
        events = self.upcoming_events(event, d, fin)
        self.assertEqual(len(events), 0)

Example 30

View license
    def test_end_repeat(self):
        """Test that an event's end_repeat is respected."""
        event = create_event(
            start_date=(2014, 3, 1),
            end_date=(2014, 3, 3),
            created_by=self.user,
            title="Veronika",
            description="Testing 1 2 3",
            repeat="WEEKLY",
            end_repeat=date(2014, 3, 10),
            utc=True
        )
        d = make_aware(datetime(2014, 3, 6), utc)
        fin = d + timedelta(days=90)
        events = self.upcoming_events(event, d, fin)
        self.assertEqual(len(events), 1)
        self.assertEqual(events[0][0].date(), date(2014, 3, 8))
        self.assertEqual(events[0][1].title, event.title)

Example 31

View license
    def test_event_starts_outside_of_bound(self):
        """
        Passing an event that starts outside of 'finish' argument
        should return an empty list.
        """
        event = create_event(
            start_date=(2015, 3, 1),
            end_date=(2015, 3, 3),
            created_by=self.user,
            title="Veronica",
            description="Testing 1 2 3",
            repeat="WEEKLY",
            utc=True
        )
        d = make_aware(datetime(2014, 3, 6), utc)
        # set finish arg to 90 days from d
        fin = d + timedelta(days=90)
        events = self.upcoming_events(event, d, fin)
        self.assertEqual(len(events), 0)

Example 32

View license
    def test_different_num(self):
        """
        If the 'num' argument is supplied, should return 'num' number of
        events.
        """
        num = 8
        event = create_event(
            start_date=(2014, 3, 1),
            end_date=(2014, 3, 3),
            created_by=self.user,
            title="Veronica",
            description="Testing 1 2 3",
            repeat="WEEKLY",
            utc=True
        )
        d = make_aware(datetime(2014, 3, 6), utc)
        fin = d + timedelta(days=900)
        events = self.upcoming_events(event, d, fin, num)
        self.assertEqual(len(events), num)

Example 33

View license
    def test_hap_no_repeat(self):
        event = create_event(
            start_date=(2015, 6, 14, 20),
            end_date=(2015, 6, 14, 22),
            created_by=self.user,
            title="Happening",
            description="Testing 1 2 3",
            utc=True
        )
        for hr in (20, 21, 22):
            d = make_aware(datetime(2015, 6, 14, hr), utc)
            events = self.hap(event, d)
            self.assertEqual(events, 1)
        for hr in (19, 23):
            d = make_aware(datetime(2015, 6, 14, hr), utc)
            events = self.hap(event, d)
            self.assertEqual(events, 0)

Example 34

View license
    def test_hap_weekday_repeat_future(self):
        event = create_event(
            start_date=(2016, 6, 1, 20),
            end_date=(2016, 6, 1, 22),
            created_by=self.user,
            title="Happening",
            description="Testing 1 2 3",
            repeat="WEEKDAY",
            utc=True
        )
        d = make_aware(datetime(2015, 6, 1, 21), utc)
        events = self.hap(event, d)
        self.assertEqual(events, 0)
        d = make_aware(datetime(2015, 6, 1, 20), utc)
        events = self.hap(event, d)
        self.assertEqual(events, 0)
        d = make_aware(datetime(2015, 6, 1, 21, 59), utc)
        events = self.hap(event, d)
        self.assertEqual(events, 0)

Example 35

Project: django-rq-dashboard
Source File: views.py
View license
def serialize_job(job):
    return dict(
        id=job.id,
        key=job.key,
        created_at=timezone.make_aware(job.created_at, utc),
        enqueued_at=timezone.make_aware(job.enqueued_at,
                                        utc) if job.enqueued_at else None,
        ended_at=timezone.make_aware(job.ended_at,
                                     utc) if job.ended_at else None,
        origin=job.origin,
        result=job.result,
        exc_info=job.exc_info,
        description=job.description,
    )

Example 36

Project: cgstudiomap
Source File: operations.py
View license
    def convert_datetimefield_value(self, value, expression, connection, context):
        if value is not None:
            if not isinstance(value, datetime.datetime):
                value = parse_datetime(value)
            if settings.USE_TZ:
                value = timezone.make_aware(value, self.connection.timezone)
        return value

Example 37

Project: cgstudiomap
Source File: expressions.py
View license
    def convert_value(self, value, expression, connection, context):
        if settings.USE_TZ:
            if value is None:
                raise ValueError(
                    "Database returned an invalid value in QuerySet.datetimes(). "
                    "Are time zone definitions for your database and pytz installed?"
                )
            value = value.replace(tzinfo=None)
            value = timezone.make_aware(value, self.tzinfo)
        return value

Example 38

Project: django
Source File: operations.py
View license
    def convert_datetimefield_value(self, value, expression, connection, context):
        if value is not None:
            if not isinstance(value, datetime.datetime):
                value = parse_datetime(value)
            if settings.USE_TZ:
                value = timezone.make_aware(value, self.connection.timezone)
        return value

Example 39

Project: django
Source File: datetime.py
View license
    def convert_value(self, value, expression, connection, context):
        if isinstance(self.output_field, DateTimeField):
            if settings.USE_TZ:
                if value is None:
                    raise ValueError(
                        "Database returned an invalid datetime value. "
                        "Are time zone definitions for your database installed?"
                    )
                value = value.replace(tzinfo=None)
                value = timezone.make_aware(value, self.tzinfo)
        elif isinstance(value, datetime):
            if isinstance(self.output_field, DateField):
                value = value.date()
            elif isinstance(self.output_field, TimeField):
                value = value.time()
        return value

Example 40

Project: django
Source File: tests.py
View license
    @unittest.skipUnless(connection.vendor == 'mysql', "MySQL specific SQL used")
    def test_datetime_output_field(self):
        with register_lookup(models.PositiveIntegerField, DateTimeTransform):
            ut = MySQLUnixTimestamp.objects.create(timestamp=time.time())
            y2k = timezone.make_aware(datetime(2000, 1, 1))
            self.assertSequenceEqual(MySQLUnixTimestamp.objects.filter(timestamp__as_datetime__gt=y2k), [ut])

Example 41

Project: django
Source File: test_datetime.py
View license
    def test_extract_year_greaterthan_lookup(self):
        start_datetime = datetime(2015, 6, 15, 14, 10)
        end_datetime = datetime(2016, 6, 15, 14, 10)
        if settings.USE_TZ:
            start_datetime = timezone.make_aware(start_datetime, is_dst=False)
            end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        self.create_model(end_datetime, start_datetime)

        qs = DTModel.objects.filter(start_datetime__year__gt=2015)
        self.assertEqual(qs.count(), 1)
        self.assertEqual(str(qs.query).lower().count('extract'), 0)
        qs = DTModel.objects.filter(start_datetime__year__gte=2015)
        self.assertEqual(qs.count(), 2)
        self.assertEqual(str(qs.query).lower().count('extract'), 0)

Example 42

Project: django
Source File: test_datetime.py
View license
    def test_extract_year_lessthan_lookup(self):
        start_datetime = datetime(2015, 6, 15, 14, 10)
        end_datetime = datetime(2016, 6, 15, 14, 10)
        if settings.USE_TZ:
            start_datetime = timezone.make_aware(start_datetime, is_dst=False)
            end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        self.create_model(end_datetime, start_datetime)

        qs = DTModel.objects.filter(start_datetime__year__lt=2016)
        self.assertEqual(qs.count(), 1)
        self.assertEqual(str(qs.query).count('extract'), 0)
        qs = DTModel.objects.filter(start_datetime__year__lte=2016)
        self.assertEqual(qs.count(), 2)
        self.assertEqual(str(qs.query).count('extract'), 0)

Example 43

Project: django
Source File: test_datetime.py
View license
    def test_extract_year_func(self):
        start_datetime = microsecond_support(datetime(2015, 6, 15, 14, 30, 50, 321))
        end_datetime = microsecond_support(datetime(2016, 6, 15, 14, 10, 50, 123))
        if settings.USE_TZ:
            start_datetime = timezone.make_aware(start_datetime, is_dst=False)
            end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        self.create_model(end_datetime, start_datetime)
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=ExtractYear('start_datetime')).order_by('start_datetime'),
            [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=ExtractYear('start_date')).order_by('start_datetime'),
            [(start_datetime, start_datetime.year), (end_datetime, end_datetime.year)],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertEqual(DTModel.objects.filter(start_datetime__year=ExtractYear('start_datetime')).count(), 2)

Example 44

Project: django
Source File: test_datetime.py
View license
    def test_extract_month_func(self):
        start_datetime = microsecond_support(datetime(2015, 6, 15, 14, 30, 50, 321))
        end_datetime = microsecond_support(datetime(2016, 6, 15, 14, 10, 50, 123))
        if settings.USE_TZ:
            start_datetime = timezone.make_aware(start_datetime, is_dst=False)
            end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        self.create_model(end_datetime, start_datetime)
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=ExtractMonth('start_datetime')).order_by('start_datetime'),
            [(start_datetime, start_datetime.month), (end_datetime, end_datetime.month)],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=ExtractMonth('start_date')).order_by('start_datetime'),
            [(start_datetime, start_datetime.month), (end_datetime, end_datetime.month)],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertEqual(DTModel.objects.filter(start_datetime__month=ExtractMonth('start_datetime')).count(), 2)

Example 45

Project: django
Source File: test_datetime.py
View license
    def test_extract_day_func(self):
        start_datetime = microsecond_support(datetime(2015, 6, 15, 14, 30, 50, 321))
        end_datetime = microsecond_support(datetime(2016, 6, 15, 14, 10, 50, 123))
        if settings.USE_TZ:
            start_datetime = timezone.make_aware(start_datetime, is_dst=False)
            end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        self.create_model(end_datetime, start_datetime)
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=ExtractDay('start_datetime')).order_by('start_datetime'),
            [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=ExtractDay('start_date')).order_by('start_datetime'),
            [(start_datetime, start_datetime.day), (end_datetime, end_datetime.day)],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertEqual(DTModel.objects.filter(start_datetime__day=ExtractDay('start_datetime')).count(), 2)

Example 46

Project: django
Source File: test_datetime.py
View license
    def test_extract_hour_func(self):
        start_datetime = microsecond_support(datetime(2015, 6, 15, 14, 30, 50, 321))
        end_datetime = microsecond_support(datetime(2016, 6, 15, 14, 10, 50, 123))
        if settings.USE_TZ:
            start_datetime = timezone.make_aware(start_datetime, is_dst=False)
            end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        self.create_model(end_datetime, start_datetime)
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=ExtractHour('start_datetime')).order_by('start_datetime'),
            [(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=ExtractHour('start_time')).order_by('start_datetime'),
            [(start_datetime, start_datetime.hour), (end_datetime, end_datetime.hour)],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertEqual(DTModel.objects.filter(start_datetime__hour=ExtractHour('start_datetime')).count(), 2)

Example 47

Project: django
Source File: test_datetime.py
View license
    def test_extract_minute_func(self):
        start_datetime = microsecond_support(datetime(2015, 6, 15, 14, 30, 50, 321))
        end_datetime = microsecond_support(datetime(2016, 6, 15, 14, 10, 50, 123))
        if settings.USE_TZ:
            start_datetime = timezone.make_aware(start_datetime, is_dst=False)
            end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        self.create_model(end_datetime, start_datetime)
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=ExtractMinute('start_datetime')).order_by('start_datetime'),
            [(start_datetime, start_datetime.minute), (end_datetime, end_datetime.minute)],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=ExtractMinute('start_time')).order_by('start_datetime'),
            [(start_datetime, start_datetime.minute), (end_datetime, end_datetime.minute)],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertEqual(DTModel.objects.filter(start_datetime__minute=ExtractMinute('start_datetime')).count(), 2)

Example 48

Project: django
Source File: test_datetime.py
View license
    def test_extract_second_func(self):
        start_datetime = microsecond_support(datetime(2015, 6, 15, 14, 30, 50, 321))
        end_datetime = microsecond_support(datetime(2016, 6, 15, 14, 10, 50, 123))
        if settings.USE_TZ:
            start_datetime = timezone.make_aware(start_datetime, is_dst=False)
            end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        self.create_model(end_datetime, start_datetime)
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=ExtractSecond('start_datetime')).order_by('start_datetime'),
            [(start_datetime, start_datetime.second), (end_datetime, end_datetime.second)],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertQuerysetEqual(
            DTModel.objects.annotate(extracted=ExtractSecond('start_time')).order_by('start_datetime'),
            [(start_datetime, start_datetime.second), (end_datetime, end_datetime.second)],
            lambda m: (m.start_datetime, m.extracted)
        )
        self.assertEqual(DTModel.objects.filter(start_datetime__second=ExtractSecond('start_datetime')).count(), 2)

Example 49

Project: django
Source File: test_datetime.py
View license
    def test_extract_func_explicit_timezone_priority(self):
        start_datetime = microsecond_support(datetime(2015, 6, 15, 23, 30, 1, 321))
        end_datetime = microsecond_support(datetime(2015, 6, 16, 13, 11, 27, 123))
        start_datetime = timezone.make_aware(start_datetime, is_dst=False)
        end_datetime = timezone.make_aware(end_datetime, is_dst=False)
        self.create_model(start_datetime, end_datetime)
        melb = pytz.timezone('Australia/Melbourne')

        with timezone.override(melb):
            model = DTModel.objects.annotate(
                day_melb=Extract('start_datetime', 'day'),
                day_utc=Extract('start_datetime', 'day', tzinfo=timezone.utc),
            ).order_by('start_datetime').get()
            self.assertEqual(model.day_melb, 16)
            self.assertEqual(model.day_utc, 15)

Example 50

Project: django-oscar
Source File: utils.py
View license
def format_datetime(dt, format=None):
    """
    Takes an instance of datetime, converts it to the current timezone and
    formats it as a string. Use this instead of
    django.core.templatefilters.date, which expects localtime.

    :param format: Common will be settings.DATETIME_FORMAT or
                   settings.DATE_FORMAT, or the resp. shorthands
                   ('DATETIME_FORMAT', 'DATE_FORMAT')
    """
    if is_naive(dt):
        localtime = make_aware(dt, get_current_timezone())
        logging.warning(
            "oscar.core.utils.format_datetime received native datetime")
    else:
        localtime = dt.astimezone(get_current_timezone())
    return date_filter(localtime, format)