Python django.utils.timezone.timedelta() Examples

The following are 30 code examples of django.utils.timezone.timedelta(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.timezone , or try the search function .
Example #1
Source File: factories.py    From pycon with MIT License 6 votes vote down vote up
def _create(cls, model_class, *args, **kwargs):
        specified_deadlines = {}

        for deadline in Deadline.TYPES:
            _type = deadline[0]

            value = kwargs.pop(f"active_{_type}", None)
            specified_deadlines[_type] = value

        instance = super()._create(model_class, *args, **kwargs)

        for _type, value in specified_deadlines.items():
            if value is True:
                instance.deadlines.add(DeadlineFactory(conference=instance, type=_type))
            elif value is False:
                instance.deadlines.add(
                    DeadlineFactory(
                        conference=instance,
                        type=_type,
                        start=timezone.now() - timezone.timedelta(days=10),
                        end=timezone.now() - timezone.timedelta(days=5),
                    )
                )

        return instance 
Example #2
Source File: test_views.py    From scale with Apache License 2.0 6 votes vote down vote up
def test_time_successful(self):
        """Tests successfully calling the get recipes by time"""
        yesterday = timezone.now().date() - timezone.timedelta(days=1)
        yesterday = yesterday.isoformat() + 'T00:00:00Z'
        today = timezone.now().date()
        today = today.isoformat() + 'T00:00:00Z'
        tomorrow = timezone.now().date() + timezone.timedelta(days=1)
        tomorrow = tomorrow.isoformat() + 'T00:00:00Z'

        url = '/%s/recipes/?started=%s&ended=%s' % (self.api, today, tomorrow)
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
        result = json.loads(response.content)
        results = result['results']
        self.assertEqual(len(results), 5)

        url = '/%s/recipes/?started=%s&ended=%s' % (self.api, yesterday, today)
        response = self.client.get(url)
        self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
        result = json.loads(response.content)
        results = result['results']
        self.assertEqual(len(results), 0) 
Example #3
Source File: test_models.py    From django-rest-messaging with ISC License 6 votes vote down vote up
def test_check_callback_and_save(self):
        # we ensure a user may by default not send more than 50 messages a day
        Message.objects.filter(sender=self.participant1).count()
        r = 100
        for i in range(r):
            try:
                m = Message(sender=self.participant1, thread=self.thread1, body="hi")
                m.save()
            except Exception:
                pass
        # we have more than 50 messages (more in setUp)
        self.assertEqual(50, Message.objects.filter(sender=self.participant1).count())
        # the limit is only in the last 24 hours
        Message.objects.filter(sender=self.participant1).update(sent_at=now() - timedelta(days=1, seconds=1))
        last = Message.objects.filter(sender=self.participant1).latest('id')
        new = Message.objects.create(sender=self.participant1, thread=self.thread1, body="hi")
        self.assertEqual(new.id, last.id + 1) 
Example #4
Source File: test_views.py    From django-rest-messaging with ISC License 6 votes vote down vote up
def test_list_messages_in_thread(self):
        # no authentication
        response = self.client_unauthenticated.get("{0}{1}/list_messages_in_thread/".format(self.url, self.thread1.id))
        self.assertEqual(403, response.status_code)
        # no permission
        response = self.client_authenticated.get("{0}{1}/list_messages_in_thread/".format(self.url, self.thread_unrelated.id))
        self.assertEqual(403, response.status_code)
        # ok
        # participant 3 has read the 2 last messages, 1 only the first
        p1 = Participation.objects.create(participant=self.participant3, thread=self.thread3)
        p1.date_last_check = now() - timedelta(days=1)
        p1.save()
        p2 = Participation.objects.create(participant=self.participant1, thread=self.thread3)
        p2.date_last_check = now() - timedelta(days=2)
        p2.save()
        # we change the date of the messages
        self.m31.sent_at = p1.date_last_check = now() - timedelta(days=3)
        self.m31.save()
        self.m32.sent_at = p1.date_last_check = now() - timedelta(days=1, hours=12)
        self.m32.save()
        response = self.client_authenticated.get("{0}{1}/list_messages_in_thread/".format(self.url, self.thread3.id))
        messages_dct = parse_json_response(response.data)
        messages = messages_dct["results"]
        self.assertEqual([self.m33.id, self.m32.id, self.m31.id], [m["id"] for m in messages])
        self.assertEqual([set([]), set([self.participant3.id]), set([self.participant1.id, self.participant3.id])], [set(m["readers"]) for m in messages]) 
Example #5
Source File: test_views.py    From django-rest-messaging with ISC License 6 votes vote down vote up
def test_get_queryset(self):
        # no authentication
        response = self.client_unauthenticated.get(self.url)
        self.assertEqual(403, response.status_code)
        # ok
        # participant 3 has read the 2 last messages, 1 only the first
        p1 = Participation.objects.create(participant=self.participant3, thread=self.thread3)
        p1.date_last_check = now() - timedelta(days=1)
        p1.save()
        p2 = Participation.objects.create(participant=self.participant1, thread=self.thread3)
        p2.date_last_check = now() - timedelta(days=2)
        p2.save()
        response = self.client_authenticated.get(self.url)
        self.assertEqual(200, response.status_code)
        messages_dct = parse_json_response(response.data)
        messages = messages_dct["results"]
        self.assertEqual(3, len(messages))
        self.assertEqual(messages[0]["id"], self.m33.id)
        self.assertEqual(messages[1]["id"], self.m22.id)
        self.assertEqual(messages[2]["id"], self.m11.id)
        self.assertEqual([], messages[0]["readers"])
        self.assertEqual(messages[0]["is_notification"], True)  # not read
        self.assertEqual(messages[1]["is_notification"], False)  # because written by the user himself
        self.assertEqual(messages[2]["is_notification"], False)  # because written by the user himself 
Example #6
Source File: models.py    From pedidosanonimos with MIT License 6 votes vote down vote up
def status(self):
        last_message = self.last_message
        status = None

        if not last_message:
            status = self.STATUS.waiting_user
        elif not last_message.is_from_user:
            appeal_deadline = timezone.now() - timezone.timedelta(days=self.APPEAL_DAYS)
            if last_message.sent_at <= appeal_deadline:
                status = self.STATUS.finished
            else:
                status = self.STATUS.waiting_user
            pass
        elif last_message.is_sent:
            reply_deadline = timezone.now() - timezone.timedelta(days=self.REPLY_DAYS)
            if last_message.sent_at <= reply_deadline:
                status = self.STATUS.delayed
            else:
                status = self.STATUS.waiting_government
        else:
            status = last_message.status

        return status 
Example #7
Source File: test_digest.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def test_email_weekly_command_other_day(self):
        """Test that admin cannot digest email not on weekly digest day unless forced."""
        setattr(settings, 'DIGEST_WEEKLY_DAY', 0)

        previous = timezone.now()
        static = previous
        # make sure we're not on a scheduled digest day
        while static.weekday() == 0:
            static += timezone.timedelta(days=1)

        with patch('openach.management.commands.senddigest.timezone.now') as timezone_mock:
            timezone_mock.return_value = static
            logger.debug('Shifted timezone.now() from weekday %s to %s', previous.weekday(), static.weekday())

            create_board(board_title='New Board', days=-1)
            call_command('senddigest', 'weekly')

            self.assertEqual(len(mail.outbox), 0, 'Weekly digest email sent on wrong day')

            call_command('senddigest', 'weekly', '--force')
            self.assertEqual(len(mail.outbox), 1, 'Weekly digest email not sent when forced') 
Example #8
Source File: test_digest.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def test_email_weekly_command_digest_day(self):
        """Test that admin can send digest on the weekly digest day."""
        setattr(settings, 'DIGEST_WEEKLY_DAY', 0)

        previous = timezone.now()
        static = previous
        # find the next scheduled digest day
        while static.weekday() != 0:
            static += timezone.timedelta(days=1)

        with patch('openach.management.commands.senddigest.timezone.now') as timezone_mock:
            timezone_mock.return_value = static
            logger.debug('Shifted timezone.now() from weekday %s to %s', previous.weekday(), static.weekday())

            create_board(board_title='New Board', days=-1)
            call_command('senddigest', 'weekly')

            self.assertEqual(len(mail.outbox), 1, 'No weekly digest email sent') 
Example #9
Source File: test_models.py    From django-rest-messaging with ISC License 6 votes vote down vote up
def test_get_lasts_messages_of_threads_check_is_notification_check_who_read(self):
        # participant 1 and 2 have read the messages, 3 no
        self.participation1.date_last_check = now() + timedelta(days=1)
        self.participation1.save()
        self.participation2.date_last_check = now() + timedelta(days=1)
        self.participation2.save()
        # we create a notification check
        with self.assertNumQueries(6):
            messages = Message.managers.get_lasts_messages_of_threads(self.participant1.id, check_who_read=True, check_is_notification=True)
            # the ordering has not been modified
            self.assertEqual([self.m33.id, self.m22.id, self.m11.id], [m.id for m in messages])
            # the second conversation has no notification because last reply comes from the current participant
            self.assertEqual(messages[1].is_notification, False)
            # the third (first in ordering) conversation has new messages
            self.assertEqual(messages[0].is_notification, True)
            # participant 1 and 2 have read Thread 1
            self.assertTrue(self.participant1.id in messages[2].readers) 
Example #10
Source File: test_api.py    From opencraft with GNU Affero General Public License v3.0 6 votes vote down vote up
def setUp(self):
        self.user = create_user_and_profile("test.user", "test.user@example.com")
        self.reference_time = timezone.now() - timezone.timedelta(hours=1)
        self.user.profile.accepted_privacy_policy = self.reference_time
        self.user.profile.save()
        self.user_data = {
            "username": "another.user",
            "password": "Thisisapassword123()",
            "email": "another.user@some.domain",
        }
        self.profile_data = {
            "full_name": "Another User",
            "accepted_privacy_policy": self.reference_time,
            "accept_paid_support": True,
            "subscribe_to_updates": True
        }
        self.account_data = {**self.user_data, **self.profile_data} 
Example #11
Source File: test_chores.py    From desec-stack with MIT License 6 votes vote down vote up
def test_inactive_user_cleanup(self):
        def create_users(kind):
            logintime = timezone.now() + timezone.timedelta(seconds=5)
            kwargs_list = [
                dict(email=f'user1+{kind}@example.com', is_active=False, last_login=None),
                dict(email=f'user2+{kind}@example.com', is_active=True, last_login=None),
                dict(email=f'user3+{kind}@example.com', is_active=False, last_login=logintime),
                dict(email=f'user4+{kind}@example.com', is_active=True, last_login=logintime),
            ]
            return (User.objects.create(**kwargs) for kwargs in kwargs_list)

        # Old users
        faketime = timezone.now() - settings.VALIDITY_PERIOD_VERIFICATION_SIGNATURE - timezone.timedelta(seconds=1)
        with mock.patch('django.db.models.fields.timezone.now', return_value=faketime):
            expired_user, _, _, _ = create_users('old')

        # New users
        create_users('new')

        all_users = set(User.objects.all())

        management.call_command('chores')
        # Check that only the expired user was deleted
        self.assertEqual(all_users - set(User.objects.all()), {expired_user}) 
Example #12
Source File: tasks.py    From opencraft with GNU Affero General Public License v3.0 6 votes vote down vote up
def delete_old_logs():
    """
    Delete old log entries.

    For performance reasons, we execute raw SQL against the LogEntry model's table.

    This task runs every day.
    """
    cutoff = timezone.now() - timezone.timedelta(days=settings.LOG_DELETION_DAYS)
    query = (
        "DELETE FROM {table} "
        "WHERE {table}.created < '{cutoff}'::timestamptz".format(
            table=LogEntry._meta.db_table,
            cutoff=cutoff.isoformat(),
        )
    )
    logger.info(query)
    with connection.cursor() as cursor:
        cursor.execute(query) 
Example #13
Source File: test_events_views.py    From fossevents.in with MIT License 6 votes vote down vote up
def test_homepage_search(client):
    event = f.EventFactory(is_published=True, name='test_event')
    f.EventFactory(is_published=True, start_date=timezone.now()-timezone.timedelta(days=9),
                   end_date=timezone.now()-timezone.timedelta(days=8))
    url = reverse('home')
    response = client.get(url, {'q': 'test'})
    assert response.status_code == 200

    # should have 'events' in the template context
    assert 'events' in response.context
    assert 'upcoming_events' in response.context
    assert 'past_events' in response.context

    assert len(response.context['events']) == 1
    assert len(response.context['upcoming_events']) == 0
    assert len(response.context['past_events']) == 0
    assert response.context['events'][0].id == event.id 
Example #14
Source File: union_story.py    From rssant with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def query_recent_by_user(cls, user_id, feed_unionids=None, days=14, limit=300, detail=False):
        """
        Deprecated since 1.4.2, use batch_get_by_feed_offset instead
        """
        if (not feed_unionids) and feed_unionids is not None:
            return []  # when feed_unionids is empty list, return empty list
        if feed_unionids:
            feed_ids = [x.feed_id for x in feed_unionids]
            feed_ids = cls._query_user_feed_ids(user_id, feed_ids)
        else:
            feed_ids = cls._query_user_feed_ids(user_id)
        dt_begin = timezone.now() - timezone.timedelta(days=days)
        q = Story.objects.filter(feed_id__in=feed_ids)\
            .filter(dt_published__gte=dt_begin)
        detail = Detail.from_schema(detail, StoryDetailSchema)
        q = q.defer(*detail.exclude_fields)
        q = q.order_by('-dt_published')[:limit]
        storys = list(q.all())
        union_storys = cls._query_union_storys(
            user_id=user_id, storys=storys, detail=detail)
        return union_storys 
Example #15
Source File: cron.py    From oh-my-rss with MIT License 6 votes vote down vote up
def clean_history_data():
    """
    清除历史数据
    :return:
    """
    logger.info('开始清理历史数据')

    lastweek = datetime.now() - timedelta(days=7)
    last3month = datetime.now() - timedelta(days=90)
    lastyear = datetime.now() - timedelta(days=365)

    # (, 10),直接删除
    Article.objects.filter(site__star__lt=10, ctime__lte=lastweek).delete()

    # [10, 20),创建时间超过 3 个月,内容置空
    Article.objects.filter(site__star__gte=10, site__star__lt=20, ctime__lte=last3month).update(content=' ')

    # [20, ),创建时间超过一年,内容置空
    Article.objects.filter(site__star__gte=20, ctime__lte=lastyear).update(content=' ')

    # 压缩数据库
    vacuum_sqlite_db()

    logger.info('历史数据清理完毕') 
Example #16
Source File: test_events.py    From pycon with MIT License 6 votes vote down vote up
def test_query_events_with_zero_events(graphql_client, conference_factory):
    now = timezone.now()

    conference = conference_factory(start=now, end=now + timezone.timedelta(days=3))

    resp = graphql_client.query(
        """query($code: String!) {
            conference(code: $code) {
                events {
                    slug
                }
            }
        }""",
        variables={"code": conference.code},
    )

    assert not resp.get("errors")

    assert len(resp["data"]["conference"]["events"]) == 0 
Example #17
Source File: test_events.py    From pycon with MIT License 6 votes vote down vote up
def test_query_events_image(rf, graphql_client, conference_factory, event_factory):
    now = timezone.now()
    request = rf.get("/")

    conference = conference_factory(start=now, end=now + timezone.timedelta(days=3))
    event = event_factory(conference=conference, latitude=1, longitude=1)

    resp = graphql_client.query(
        """query($code: String!) {
            conference(code: $code) {
                events {
                    image
                }
            }
        }""",
        variables={"code": conference.code},
    )

    assert not resp.get("errors")

    assert len(resp["data"]["conference"]["events"]) == 1
    events = resp["data"]["conference"]["events"]
    events[0]["image"] == get_image_url_from_request(request, event.image) 
Example #18
Source File: test_conference.py    From pycon with MIT License 6 votes vote down vote up
def test_is_cfp_open(graphql_client, conference_factory, deadline_factory, cfp_open):
    now = timezone.now()

    conference = conference_factory(timezone=pytz.timezone("America/Los_Angeles"))

    deadline_factory(
        start=now - timezone.timedelta(days=1),
        end=now + timezone.timedelta(days=1) if cfp_open else now,
        conference=conference,
        type="cfp",
    )

    resp = graphql_client.query(
        """
        query($code: String!) {
            conference(code: $code) {
                isCFPOpen
            }
        }
        """,
        variables={"code": conference.code},
    )

    assert resp["data"]["conference"]["isCFPOpen"] is cfp_open 
Example #19
Source File: test_profile.py    From online-judge with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_update_contest(self):
        _now = timezone.now()
        for contest in (
            create_contest(
                key='finished_contest',
                start_time=_now - timezone.timedelta(days=100),
                end_time=_now - timezone.timedelta(days=10),
                is_visible=True,
            ),
            create_contest(
                key='inaccessible_contest',
                start_time=_now - timezone.timedelta(days=100),
                end_time=_now + timezone.timedelta(days=10),
            ),
        ):
            with self.subTest(name=contest.name):
                self.profile.current_contest = create_contest_participation(
                    contest=contest,
                    user=self.profile,
                )
                self.assertIsNotNone(self.profile.current_contest)
                self.profile.update_contest()
                self.assertIsNone(self.profile.current_contest) 
Example #20
Source File: email_mirror.py    From zulip with Apache License 2.0 6 votes vote down vote up
def get_usable_missed_message_address(address: str) -> MissedMessageEmailAddress:
    token = get_missed_message_token_from_address(address)
    try:
        mm_address = MissedMessageEmailAddress.objects.select_related().get(
            email_token=token,
            timestamp__gt=timezone_now() - timedelta(seconds=MissedMessageEmailAddress.EXPIRY_SECONDS),
        )
    except MissedMessageEmailAddress.DoesNotExist:
        raise ZulipEmailForwardError("Missed message address expired or doesn't exist.")

    if not mm_address.is_usable():
        # Technical, this also checks whether the event is expired,
        # but that case is excluded by the logic above.
        raise ZulipEmailForwardError("Missed message address out of uses.")

    return mm_address 
Example #21
Source File: serializers.py    From opencraft with GNU Affero General Public License v3.0 6 votes vote down vote up
def validate_accepted_privacy_policy(self, value):
        """
        Ensure that no account is created without a policy acceptance date.
        """
        if value is None:
            raise ValidationError("You must accept the privacy policy to register.")
        if (
                self.instance
                and self.instance.accepted_privacy_policy
                and value < self.instance.accepted_privacy_policy
        ):
            raise ValidationError(
                "New policy acceptance date cannot be earlier than previous acceptance date."
            )
        if value >= timezone.now() + timezone.timedelta(hours=1):
            raise ValidationError("Cannot accept policy for a future date.")
        return value 
Example #22
Source File: feed_creation.py    From rssant with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def query_id_urls_by_status(cls, status, survival_seconds=None):
        q = FeedCreation.objects.filter(status=status)
        if survival_seconds:
            deadline = timezone.now() - timezone.timedelta(seconds=survival_seconds)
            q = q.filter(dt_created__lt=deadline)
        id_urls = [(x.id, x.url) for x in q.only('id', 'url').all()]
        return id_urls 
Example #23
Source File: feed_creation.py    From rssant with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delete_by_status(status=None, survival_seconds=None):
        q = FeedCreation.objects
        if status:
            q = q.filter(status=status)
        if survival_seconds:
            deadline = timezone.now() - timezone.timedelta(seconds=survival_seconds)
            q = q.filter(dt_created__lt=deadline)
        num_deleted, __ = q.delete()
        return num_deleted 
Example #24
Source File: test_problem.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUpTestData(self):
        super().setUpTestData()
        self.users.update({
            'staff_solution_see_all': create_user(
                username='staff_solution_see_all',
                user_permissions=('see_private_solution',),
            ),
        })

        _now = timezone.now()

        self.basic_solution = create_solution(problem='basic')

        self.private_solution = create_solution(
            problem='private',
            is_public=False,
            publish_on=_now - timezone.timedelta(days=100),
        )

        self.unpublished_problem = create_problem(
            code='unpublished',
            name='Unpublished',
            authors=('staff_problem_edit_own',),
        )
        self.unpublished_solution = create_solution(
            problem=self.unpublished_problem,
            is_public=False,
            publish_on=_now + timezone.timedelta(days=100),
            authors=('normal',),
        ) 
Example #25
Source File: test_question.py    From notes with GNU General Public License v3.0 5 votes vote down vote up
def test_was_published_recently_with_old_question(self):
        pub_date = timezone.now() - timezone.timedelta(days=30)
        question = self.create_question(pub_date=pub_date)

        self.assertIs(question.was_published_recently(), False) 
Example #26
Source File: util.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_defaults(self, required_kwargs, kwargs):
        _now = timezone.now()
        return {
            'name': required_kwargs['key'],
            'description': '',
            'start_time': _now - timezone.timedelta(days=100),
            'end_time': _now + timezone.timedelta(days=100),
        } 
Example #27
Source File: util.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_defaults(self, required_kwargs, kwargs):
        _now = timezone.now()
        return {
            'slug': required_kwargs['title'],
            'publish_on': _now - timezone.timedelta(days=100),
        } 
Example #28
Source File: test_introspection_endpoint.py    From django-oidc-provider with MIT License 5 votes vote down vote up
def test_token_expired_returns_inactive(self):
        self.token.expires_at = timezone.now() - timezone.timedelta(seconds=60)
        self.token.save()
        response = self._make_request()
        self._assert_inactive(response) 
Example #29
Source File: test_contest.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_live_participation(self):
        participation = ContestParticipation.objects.get(
            contest=self.hidden_scoreboard_contest,
            user=self.users['normal'].profile,
            virtual=ContestParticipation.LIVE,
        )
        self.assertTrue(participation.live)
        self.assertFalse(participation.spectate)
        self.assertEqual(participation.end_time, participation.contest.end_time)
        self.assertFalse(participation.ended)
        self.assertIsInstance(participation.time_remaining, timezone.timedelta) 
Example #30
Source File: utils.py    From django-oidc-provider with MIT License 5 votes vote down vote up
def create_fake_token(user, scopes, client):
    expires_at = timezone.now() + timezone.timedelta(seconds=60)
    token = Token(user=user, client=client, expires_at=expires_at)
    token.scope = scopes

    token.save()

    return token