Python django.utils.timezone.timedelta() Examples

The following are 30 code examples for showing how to use django.utils.timezone.timedelta(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.utils.timezone , or try the search function .

Example 1
Project: open-synthesis   Author: twschiller   File: test_digest.py    License: 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 2
Project: open-synthesis   Author: twschiller   File: test_digest.py    License: 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 3
Project: django-rest-messaging   Author: raphaelgyory   File: test_views.py    License: 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 4
Project: django-rest-messaging   Author: raphaelgyory   File: test_views.py    License: 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
Project: django-rest-messaging   Author: raphaelgyory   File: test_models.py    License: 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 6
Project: django-rest-messaging   Author: raphaelgyory   File: test_models.py    License: 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 7
Project: desec-stack   Author: desec-io   File: test_chores.py    License: 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 8
Project: fossevents.in   Author: fossevents   File: test_events_views.py    License: 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 9
Project: pycon   Author: pythonitalia   File: test_events.py    License: 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 10
Project: pycon   Author: pythonitalia   File: test_events.py    License: 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 11
Project: pycon   Author: pythonitalia   File: test_conference.py    License: 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 12
Project: pycon   Author: pythonitalia   File: factories.py    License: 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 13
Project: zulip   Author: zulip   File: email_mirror.py    License: 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 14
Project: oh-my-rss   Author: richshaw2015   File: cron.py    License: 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 15
Project: opencraft   Author: open-craft   File: tasks.py    License: 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 16
Project: opencraft   Author: open-craft   File: serializers.py    License: 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 17
Project: opencraft   Author: open-craft   File: test_api.py    License: 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 18
Project: scale   Author: ngageoint   File: test_views.py    License: 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 19
Project: pedidosanonimos   Author: okfn-brasil   File: models.py    License: 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 20
Project: online-judge   Author: DMOJ   File: test_profile.py    License: 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 21
Project: rssant   Author: anyant   File: union_story.py    License: 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 22
Project: django-ads   Author: razisayyed   File: models.py    License: Apache License 2.0 5 votes vote down vote up
def now_plus_1_day():
    return timezone.now() + timezone.timedelta(days=1) 
Example 23
Project: open-synthesis   Author: twschiller   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def was_published_recently(self):
        """Return True iff the Board was created recently."""
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now 
Example 24
Project: open-synthesis   Author: twschiller   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, key, delta):
        """Initialize Digest Frequency.

        :param key: unique identifier, used in database
        :param delta: timedelta covered by the frequency, or None (e.g., 7 days)
        """
        self.key = key
        self.delta = delta 
Example 25
Project: open-synthesis   Author: twschiller   File: test_digest.py    License: GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super().setUp()
        self.daily = self.user
        self.weekly = self.other

        def setup_user(user, freq):
            user.date_joined = timezone.now() + datetime.timedelta(days=-2)
            user.save()
            user.settings.digest_frequency = freq.key
            user.settings.save()

        setup_user(self.daily, DigestFrequency.daily)
        setup_user(self.weekly, DigestFrequency.weekly) 
Example 26
Project: django-rest-messaging   Author: raphaelgyory   File: models.py    License: ISC License 5 votes vote down vote up
def return_daily_messages_count(self, sender):
        """ Returns the number of messages sent in the last 24 hours so we can ensure the user does not exceed his messaging limits """
        h24 = now() - timedelta(days=1)
        return Message.objects.filter(sender=sender, sent_at__gte=h24).count() 
Example 27
Project: django-rest-messaging   Author: raphaelgyory   File: test_models.py    License: ISC License 5 votes vote down vote up
def test_get_all_messages_in_thread(self):
        # we change the date of the messages
        self.m31.sent_at = self.p2.date_last_check = now() - timedelta(days=3)
        self.m31.save()
        self.m32.sent_at = self.p2.date_last_check = now() - timedelta(days=1, hours=12)
        self.m32.save()
        # we get all the messages
        with self.assertNumQueries(3):
            messages = Message.managers.get_all_messages_in_thread(self.participant1.id, self.thread3.id)
            self.assertEqual([self.m33.id, self.m32.id, self.m31.id], [m.id for m in messages])
            self.assertEqual(set(messages[2].readers), set([self.participant1.id, self.participant3.id]))  # we do not care about the order of the readers
            self.assertEqual(messages[1].readers, [self.participant3.id])
            self.assertEqual(messages[0].readers, []) 
Example 28
Project: desec-stack   Author: desec-io   File: test_chores.py    License: MIT License 5 votes vote down vote up
def test_captcha_cleanup(self):
        faketime = timezone.now() - settings.CAPTCHA_VALIDITY_PERIOD - timezone.timedelta(seconds=1)
        with mock.patch('django.db.models.fields.timezone.now', return_value=faketime):
            captcha1 = Captcha.objects.create()

        captcha2 = Captcha.objects.create()
        self.assertGreaterEqual((captcha2.created - captcha1.created).total_seconds(), 3601)

        management.call_command('chores')
        self.assertEqual(list(Captcha.objects.all()), [captcha2]) 
Example 29
Project: woid   Author: vitorfs   File: services_url.py    License: Apache License 2.0 5 votes vote down vote up
def services_url(slug, delta):
    today = timezone.now()
    date = today - timezone.timedelta(delta)
    return r('services:day', args=(slug, date.year, str(date.month).zfill(2), str(date.day).zfill(2),)) 
Example 30
Project: woid   Author: vitorfs   File: services_url.py    License: Apache License 2.0 5 votes vote down vote up
def services_url_name(slug, delta):
    today = timezone.now()
    date = today - timezone.timedelta(delta)
    return date.strftime('%A').lower()