Python django.utils.timezone.datetime() Examples

The following are 30 code examples for showing how to use django.utils.timezone.datetime(). 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: django-idcops   Author: Wenvki   File: models.py    License: Apache License 2.0 6 votes vote down vote up
def _dict(self):
        exclude = ['operator_id', 'creator_id', 'created', 'modified']
        opts = self._meta
        data = {}
        keys = [f.attname for f in opts.fields]
        for f in chain(opts.many_to_many):
            #if isinstance(f, models.ManyToManyField):
            if self.pk is None:
                data[f.name] = []
            else:
                data[f.name] = list(f.value_from_object(self).values_list('pk', flat=True))
        original = { k:self.__dict__.get(k) for k in keys if k not in exclude }
        data.update(**original)
        for key, value in data.items():
            if isinstance(value, timezone.datetime):
                value = formats.localize(timezone.template_localtime(value))
            data.update(**{key: value})
        return data 
Example 2
Project: woid   Author: vitorfs   File: crawlers.py    License: Apache License 2.0 6 votes vote down vote up
def update_top_stories(self):
        try:
            posts = self.client.get_top_posts()
            today = timezone.now()
            for post in posts:
                code = post['slug']
                story, created = Story.objects.get_or_create(
                    service=self.service,
                    code=code,
                    date=timezone.datetime(today.year, today.month, today.day, tzinfo=timezone.get_current_timezone())
                )

                if created:
                    story.title = post['name']
                    story.description = post['tagline']
                    story.url = u'{0}{1}'.format(self.service.story_url, code)

                story.score = post['votes_count']
                story.comments = post['comments_count']
                story.status = Story.OK
                story.save()

        except Exception:
            logger.exception('An error occurred while executing `update_top_stores` for Product Hunt.')
            raise 
Example 3
Project: wagtail-personalisation   Author: wagtail   File: utils.py    License: MIT License 6 votes vote down vote up
def count_active_days(enable_date, disable_date):
    """Return the number of days the segment has been active.

    :param enable_date: The date the segment was enabled
    :type enable_date: timezone.datetime
    :param disable_date: The date the segment was disabled
    :type disable_date: timezone.datetime
    :returns: The amount of days a segment is/has been active
    :rtype: int

    """
    if enable_date is not None:
        if disable_date is None or disable_date <= enable_date:
            # There is no disable date, or it is not relevant.
            delta = timezone.now() - enable_date
            return delta.days
        if disable_date > enable_date:
            # There is a disable date and it is relevant.
            delta = disable_date - enable_date
            return delta.days

    return 0 
Example 4
Project: yawn   Author: aclowes   File: test_models.py    License: MIT License 6 votes vote down vote up
def test_first_ready():
    name = WorkflowName.objects.create(name='workflow1')

    # not active, shouldn't get selected
    Workflow.objects.create(
        name=name, version=1, schedule_active=False,
        next_run=timezone.now() - datetime.timedelta(hours=1)
    )
    # future run date
    Workflow.objects.create(
        name=name, version=2, schedule_active=True,
        next_run=timezone.now() + datetime.timedelta(hours=1)
    )
    ready_workflow = Workflow.objects.create(
        name=name, version=3, schedule_active=True,
        next_run=timezone.now() - datetime.timedelta(seconds=1)
    )

    workflow = Workflow.first_ready()
    assert workflow.id == ready_workflow.id 
Example 5
Project: Simple-Q-A-App-using-Python-Django   Author: arjunkomath   File: test_mixins.py    License: MIT License 6 votes vote down vote up
def test_author_required_allow_object_user(self):
        """
        The owner of the object should be able to access
        the view
        """
        request = self.factory.get('some-random-place')
        request.user = get_user_model().objects.create_user(
            username='test_user',
            password='top_secret'
        )
        question = Question.objects.create(
            title="Another Question",
            description="A not so long random text to fill this field",
            pub_date=timezone.datetime(2016, 1, 6, 0, 0, 0),
            reward=0,
            user=request.user,
            closed=False,
        )
        response = SomeAuthorRequiredView.as_view()(request, pk=question.pk)
        self.assertEqual(response.status_code, 200) 
Example 6
Project: Simple-Q-A-App-using-Python-Django   Author: arjunkomath   File: test_mixins.py    License: MIT License 6 votes vote down vote up
def test_author_required_not_allow_not_object_user(self):
        """
        A different user than the object's owner should not
        be able to access the view, a PermissionDenied should
        be raised
        """
        request = self.factory.get('some-random-place')
        request.user = AnonymousUser()
        user = get_user_model().objects.create_user(
            username='test_user',
            password='top_secret'
        )
        question = Question.objects.create(
            title="Another Question",
            description="A not so long random text to fill this field",
            pub_date=timezone.datetime(2016, 1, 6, 0, 0, 0),
            reward=0,
            user=user,
            closed=False,
        )
        with self.assertRaises(PermissionDenied):
            SomeAuthorRequiredView.as_view()(
                request, pk=question.pk) 
Example 7
Project: Simple-Q-A-App-using-Python-Django   Author: arjunkomath   File: test_models.py    License: MIT License 6 votes vote down vote up
def setUp(self):
        self.user = get_user_model().objects.create_user(
            username='test_user',
            email='test@swapps.co',
            password='top_secret'
        )
        self.other_user = get_user_model().objects.create_user(
            username='other_test_user',
            email='other_test@swapps.co',
            password='top_secret'
        )
        self.first_question = Question.objects.create(
            title="Another Question",
            description="A not so long random text to fill this field",
            pub_date=timezone.datetime(2016, 1, 6, 0, 0, 0),
            reward=0,
            user=self.user,
            closed=False,
        )
        self.first_answer = Answer.objects.create(
            question=self.first_question,
            answer_text="I hope this text is acceptable by django_markdown",
            pub_date=timezone.datetime(2016, 2, 6, 0, 0, 0),
            user=self.user,
        ) 
Example 8
Project: Simple-Q-A-App-using-Python-Django   Author: arjunkomath   File: test_models.py    License: MIT License 6 votes vote down vote up
def test_affect_reputation_by_question(self):
        """
        This test validates than the UserQAProfile method modify_reputation
        works properly when a Question instance is created.
        """
        other_qa_user = self.other_user.userqaprofile
        self.assertEqual(other_qa_user.points, 0)
        question = Question.objects.create(
            title="Additional Question",
            description="A not so long random text",
            pub_date=timezone.datetime(2016, 1, 6, 0, 0, 0),
            reward=0,
            user=self.other_user,
            closed=False,)
        self.assertTrue(isinstance(question, Question))
        other_qa_user.refresh_from_db()
        self.assertEqual(other_qa_user.points, 4) 
Example 9
Project: Simple-Q-A-App-using-Python-Django   Author: arjunkomath   File: test_models.py    License: MIT License 6 votes vote down vote up
def test_affect_reputation_by_answer(self):
        """
        This test validates than the UserQAProfile method modify_reputation
        works properly when an Answer instance is created
        """
        other_qa_user = self.other_user.userqaprofile
        self.assertEqual(other_qa_user.points, 0)
        answer = Answer.objects.create(
            question=self.first_question,
            answer_text="A text body",
            pub_date=timezone.datetime(2016, 2, 7, 0, 0, 0),
            user=self.other_user,
        )
        self.assertTrue(isinstance(answer, Answer))
        other_qa_user.refresh_from_db()
        self.assertEqual(other_qa_user.points, 4) 
Example 10
Project: Simple-Q-A-App-using-Python-Django   Author: arjunkomath   File: test_models.py    License: MIT License 6 votes vote down vote up
def test_affect_reputation_by_answercomment(self):
        """
        This test validates than the UserQAProfile method modify_reputation
        works properly when an AnswerComment instance is created, but
        there is no QA_SETTING defined inside the settings file, so the
        try block inside the save() method of the model goes for the
        except line.
        """
        other_qa_user = self.other_user.userqaprofile
        self.assertEqual(other_qa_user.points, 0)
        comment = AnswerComment.objects.create(
            answer=self.first_answer,
            comment_text="This is not so bright a comment",
            pub_date=timezone.datetime(2016, 2, 8, 0, 0, 0),
            user=self.other_user)
        self.assertTrue(isinstance(comment, AnswerComment))
        other_qa_user.refresh_from_db()
        self.assertEqual(other_qa_user.points, 0) 
Example 11
Project: Ouroboros   Author: tamuhack-org   File: admin.py    License: GNU General Public License v3.0 6 votes vote down vote up
def build_approval_email(
    application: Application, confirmation_deadline: timezone.datetime
) -> Tuple[str, str, str, None, List[str]]:
    """
    Creates a datatuple of (subject, message, html_message, from_email, [to_email]) indicating that a `User`'s
    application has been approved.
    """
    subject = f"Your {settings.EVENT_NAME} application has been approved!"

    context = {
        "first_name": application.first_name,
        "event_name": settings.EVENT_NAME,
        "confirmation_deadline": confirmation_deadline,
    }
    html_message = render_to_string("application/emails/approved.html", context)
    message = strip_tags(html_message)
    return subject, message, html_message, None, [application.user.email] 
Example 12
Project: cjworkbench   Author: CJWorkbench   File: save.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def _do_create_result(
    workflow_id: int, wf_module: WfModule, result: FetchResult, now: timezone.datetime
) -> None:
    """
    Do database manipulations for create_result().

    Modify `wf_module` in-place.

    Do *not* do the logic in ChangeDataVersionCommand. We're creating a new
    version, not doing something undoable.

    Raise WfModule.DoesNotExist or Workflow.DoesNotExist in case of a race.
    """
    with _locked_wf_module(workflow_id, wf_module):
        storedobjects.create_stored_object(
            workflow_id, wf_module.id, result.path, stored_at=now
        )
        storedobjects.enforce_storage_limits(wf_module)

        wf_module.fetch_errors = result.errors
        wf_module.is_busy = False
        wf_module.last_update_check = now
        wf_module.save(update_fields=["fetch_errors", "is_busy", "last_update_check"]) 
Example 13
Project: cjworkbench   Author: CJWorkbench   File: test_acl.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_put_entry_dup(self):
        # dup overwrites the existing entry
        user = User.objects.create()
        workflow = Workflow.objects.create(owner=user)

        dt = timezone.datetime(2018, 10, 3, 19, 28, 1, tzinfo=timezone.utc)

        workflow.acl.create(email="a@example.org", can_edit=False, created_at=dt)
        response = self._put_entry(workflow, user, "a@example.org", '{"canEdit": true}')
        self.assertEqual(response.status_code, 204)

        # No new entry added
        self.assertEqual(len(workflow.acl.all()), 1)

        # ... but entry was updated
        entry = workflow.acl.first()
        self.assertEqual(entry.email, "a@example.org")  # not changed
        self.assertEqual(entry.can_edit, True)  # changed
        self.assertEqual(entry.created_at, dt)  # not changed 
Example 14
Project: jorvik   Author: CroceRossaItaliana   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def lezione_ore(self):
        ore = self.get_from_scheda('ore')
        if not ore:
            return ore

        if "’" in ore:
            # Elaborare i valori con apostrofo (minuti)
            minutes = re.findall(r'^\d+', ore.strip())
            minutes = int(minutes[0]) if minutes else 60
            return datetime.timedelta(minutes=minutes)

        elif "," and len(ore) < 5:
            # Valori ore, minuti con virgola (1,5)
            minutes = float(ore.replace(',', '.')) * 60
            return datetime.timedelta(minutes=minutes)

        else:
            try:
                return datetime.timedelta(hours=int(ore))
            except ValueError:
                return datetime.timedelta(hours=1) 
Example 15
Project: woid   Author: vitorfs   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def month(request, slug, year, month):
    service = get_object_or_404(Service, slug=slug)
    queryset = service.stories \
        .filter(status=Story.OK, date__year=year, date__month=month) \
        .values('url', 'title') \
        .annotate(score=Sum('score'), date=Min('date')) \
        .order_by('-score')
    subtitle = timezone.datetime(int(year), int(month), 1).strftime('%b %Y')
    return stories(request, service, queryset, subtitle) 
Example 16
Project: woid   Author: vitorfs   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def day(request, slug, year, month, day):
    date = datetime.datetime(int(year), int(month), int(day))
    service = get_object_or_404(Service, slug=slug)
    queryset = service.stories.filter(status=Story.OK, date=date)[:10]
    subtitle = timezone.datetime(int(year), int(month), int(day)).strftime('%d %b %Y')
    return stories(request, service, queryset, subtitle) 
Example 17
Project: woid   Author: vitorfs   File: crawlers.py    License: Apache License 2.0 5 votes vote down vote up
def update_top_stories(self):
        try:
            stories = self.client.get_front_page_stories()
            for data in stories:
                story_data = data['data']
                story, created = Story.objects.get_or_create(service=self.service, code=story_data.get('permalink'))
                if created:
                    story.date = timezone.datetime.fromtimestamp(
                        story_data.get('created_utc'),
                        timezone.get_current_timezone()
                    )
                    story.build_url()

                score = story_data.get('score', 0)
                comments = story_data.get('num_comments', 0)

                # has_changes = (score != story.score or comments != story.comments)

                # if not story.status == Story.NEW and has_changes:
                #     update = StoryUpdate(story=story)
                #     update.comments_changes = comments - story.comments
                #     update.score_changes = score - story.score
                #     update.save()

                story.comments = comments
                story.score = score
                story.title = story_data.get('title', '')
                story.nsfw = story_data.get('over_18', False)

                story.status = Story.OK
                story.save()
        except Exception:
            logger.exception('An error occurred while executing `update_top_stores` for Reddit.')
            raise 
Example 18
Project: palanaeum   Author: Palanaeum   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def index(request):
    """
    Draw the home page.
    """
    page_length = UserSettings.get_page_length(request)
    newest_events = Event.all_visible.exclude(entries=None).prefetch_related('entries', 'tags')[:page_length]
    events_count = Event.all_visible.filter().count()
    entries_count = Entry.all_visible.filter().count()
    audio_sources_count = AudioSource.all_visible.filter().count()

    new_sources = []
    new_sources.extend(AudioSource.all_visible.order_by('-created_date')[:5])
    new_sources.extend(ImageSource.all_visible.order_by('-created_date')[:5])
    new_sources.sort(key=lambda source: source.created_date or
                                        timezone.datetime(1900, 1, 1, tzinfo=timezone.get_current_timezone()),
                     reverse=True)
    new_sources = new_sources[:5]

    related_sites = RelatedSite.objects.all()

    welcome_text = get_config('index_hello')

    return render(request, 'palanaeum/index.html', {'newest_events': newest_events, 'events_count': events_count,
                                                    'entries_count': entries_count, 'audio_sources_count': audio_sources_count,
                                                    'new_sources': new_sources, 'related_sites': related_sites,
                                                    'welcome_text': welcome_text}) 
Example 19
Project: opencraft   Author: open-craft   File: test_tasks.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super().setUp()
        self.now = timezone.datetime(2018, 8, 1, 7, 20, 12, tzinfo=timezone.utc)
        self.before_cutoff = self.now - timezone.timedelta(days=settings.LOG_DELETION_DAYS + 1)
        self.log_deletion = self.now + timezone.timedelta(days=1)

        # Some Django start-up tasks produce logs which interfere with our tests.
        LogEntry.objects.all().delete()
        # huey produces logs when running tasks, that interfere with calculations
        logging.getLogger('huey').disabled = True 
Example 20
Project: lego   Author: webkom   File: test_utils.py    License: MIT License 5 votes vote down vote up
def fake_time(y, m, d):
    dt = timezone.datetime(y, m, d)
    dt = timezone.pytz.timezone("UTC").localize(dt)
    return dt 
Example 21
Project: yawn   Author: aclowes   File: test_models.py    License: MIT License 5 votes vote down vote up
def test_next_run(mock_cron):
    next_run = timezone.datetime(2011, 1, 1, tzinfo=pytz.UTC)
    mock_cron().next_run.return_value = next_run

    name = WorkflowName.objects.create(name='workflow1')
    workflow = Workflow.objects.create(
        name=name, version=2, schedule_active=True,
        schedule='*'
    )
    assert workflow.next_run == next_run 
Example 22
Project: online-judge   Author: DMOJ   File: test_contest.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_basic_contest(self):
        self.assertTrue(self.basic_contest.show_scoreboard)
        self.assertEqual(self.basic_contest.contest_window_length, timezone.timedelta(days=101))
        self.assertIsInstance(self.basic_contest._now, timezone.datetime)
        self.assertTrue(self.basic_contest.can_join)
        self.assertIsNone(self.basic_contest.time_before_start)
        self.assertIsInstance(self.basic_contest.time_before_end, timezone.timedelta)
        self.assertFalse(self.basic_contest.ended)
        self.assertEqual(str(self.basic_contest), self.basic_contest.name)
        self.assertEqual(self.basic_contest.get_label_for_problem(0), '1') 
Example 23
Project: online-judge   Author: DMOJ   File: test_contest.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_virtual_participation(self):
        participation = create_contest_participation(
            contest='private',
            user='superuser',
            virtual=1,
        )

        self.assertFalse(participation.live)
        self.assertFalse(participation.spectate)
        self.assertEqual(participation.start, participation.real_start)
        self.assertIsInstance(participation.end_time, timezone.datetime) 
Example 24
Project: rssant   Author: anyant   File: story_tests.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        print('setUp')
        storys = []
        updated_storys = []
        now = timezone.datetime(2020, 6, 1, 12, 12, 12, tzinfo=timezone.utc)
        for i in range(200):
            dt = now + timezone.timedelta(minutes=i)
            content = f'test story content {i}' * (i % 5)
            content_hash_base64 = compute_hash_base64(content)
            summary = content[:30]
            story = {
                'unique_id': f'blog.example.com/{i}',
                'title': f'test story {i}',
                'content_hash_base64': content_hash_base64,
                'author': 'tester',
                'link': f'https://blog.example.com/{i}.html',
                'dt_published': dt,
                'dt_updated': dt,
                'summary': summary,
                'content': content,
            }
            storys.append(validate_story(story))
            updated_story = dict(story)
            updated_content = f'test story content updated {i}' * (i % 5 + 1)
            updated_story.update(
                content=updated_content,
                content_hash_base64=compute_hash_base64(updated_content),
            )
            updated_storys.append(validate_story(updated_story))
        self.storys = storys
        self.updated_storys = updated_storys

        feed = Feed(
            title='test feed',
            url='https://blog.example.com/feed.xml',
            status=FeedStatus.READY,
            dt_updated=timezone.now(),
        )
        feed.save()
        self.feed_id = feed.id 
Example 25
Project: janeway   Author: BirkbeckCTP   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def jr_one_all_dates(request, output_format, start_year, start_month, start_day, end_year, end_month, end_day,
                     compat=False, report_request_id='', requestor_id='', requestor_email='', requestor_name='',
                     customer_ID='', customer_name=''):
    return jr_one(request, output_format,
                  timezone.datetime(int(start_year), int(start_month), int(start_day),
                                    tzinfo=timezone.get_current_timezone()),
                  timezone.datetime(int(end_year), int(end_month), int(end_day),
                                    tzinfo=timezone.get_current_timezone()),
                  compat, report_request_id, requestor_id, requestor_email, requestor_name, customer_ID,
                  customer_name) 
Example 26
Project: janeway   Author: BirkbeckCTP   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def jr_one_goa_all_dates(request, output_format, start_year, start_month, start_day, end_year, end_month, end_day,
                         compat=False, report_request_id='', requestor_id='', requestor_email='', requestor_name='',
                         customer_ID='', customer_name=''):
    return jr_one_goa(request, output_format,
                      timezone.datetime(int(start_year), int(start_month), int(start_day),
                                        tzinfo=timezone.get_current_timezone()),
                      timezone.datetime(int(end_year), int(end_month), int(end_day),
                                        tzinfo=timezone.get_current_timezone()),
                      compat, report_request_id, requestor_id, requestor_email, requestor_name, customer_ID,
                      customer_name) 
Example 27
Project: janeway   Author: BirkbeckCTP   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def jr_two_all_dates(request, output_format, start_year, start_month, start_day, end_year, end_month, end_day,
                     compat=False, report_request_id='', requestor_id='', requestor_email='', requestor_name='',
                     customer_ID='', customer_name=''):
    return jr_two(request, output_format,
                  timezone.datetime(int(start_year), int(start_month), int(start_day),
                                    tzinfo=timezone.get_current_timezone()),
                  timezone.datetime(int(end_year), int(end_month), int(end_day),
                                    tzinfo=timezone.get_current_timezone()),
                  compat, report_request_id, requestor_id, requestor_email, requestor_name, customer_ID,
                  customer_name) 
Example 28
Project: Simple-Q-A-App-using-Python-Django   Author: arjunkomath   File: test_models.py    License: MIT License 5 votes vote down vote up
def test_answer(self):
        answer = Answer.objects.create(
            question=self.first_question,
            answer_text="A text body",
            pub_date=timezone.datetime(2016, 2, 7, 0, 0, 0),
            user=self.user,
        )
        self.assertTrue(isinstance(answer, Answer))
        self.assertTrue(isinstance(self.first_answer, Answer))
        self.assertEqual(self.first_answer.answer_text,
                         "I hope this text is acceptable by django_markdown")
        self.assertEqual(answer.answer_text, "A text body") 
Example 29
Project: Simple-Q-A-App-using-Python-Django   Author: arjunkomath   File: test_models.py    License: MIT License 5 votes vote down vote up
def test_answer_comment(self):
        comment = AnswerComment.objects.create(
            answer=self.first_answer,
            comment_text="This is not so bright a comment",
            pub_date=timezone.datetime(2016, 2, 8, 0, 0, 0),
            user=self.user)
        self.assertTrue(isinstance(comment, AnswerComment)) 
Example 30
Project: Simple-Q-A-App-using-Python-Django   Author: arjunkomath   File: test_models.py    License: MIT License 5 votes vote down vote up
def test_affect_reputation_by_answercomment(self):
        """
        This test validates than the UserQAProfile method modify_reputation
        works properly when an AnswerComment instance is created
        """
        other_qa_user = self.other_user.userqaprofile
        self.assertEqual(other_qa_user.points, 0)
        comment = AnswerComment.objects.create(
            answer=self.first_answer,
            comment_text="This is not so bright a comment",
            pub_date=timezone.datetime(2016, 2, 8, 0, 0, 0),
            user=self.other_user)
        self.assertTrue(isinstance(comment, AnswerComment))
        other_qa_user.refresh_from_db()
        self.assertEqual(other_qa_user.points, 4)