Python django.utils.timezone.datetime() Examples
The following are 30
code examples of django.utils.timezone.datetime().
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: admin.py From Ouroboros with GNU General Public License v3.0 | 6 votes |
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 #2
Source File: test_acl.py From cjworkbench with GNU Affero General Public License v3.0 | 6 votes |
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 #3
Source File: test_mixins.py From Simple-Q-A-App-using-Python-Django with MIT License | 6 votes |
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 #4
Source File: test_mixins.py From Simple-Q-A-App-using-Python-Django with MIT License | 6 votes |
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 #5
Source File: test_models.py From Simple-Q-A-App-using-Python-Django with MIT License | 6 votes |
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 #6
Source File: test_models.py From yawn with MIT License | 6 votes |
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 #7
Source File: save.py From cjworkbench with GNU Affero General Public License v3.0 | 6 votes |
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 #8
Source File: test_models.py From Simple-Q-A-App-using-Python-Django with MIT License | 6 votes |
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
Source File: test_models.py From Simple-Q-A-App-using-Python-Django with MIT License | 6 votes |
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
Source File: utils.py From wagtail-personalisation with MIT License | 6 votes |
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 #11
Source File: crawlers.py From woid with Apache License 2.0 | 6 votes |
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 #12
Source File: models.py From django-idcops with Apache License 2.0 | 6 votes |
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 #13
Source File: test_models.py From Simple-Q-A-App-using-Python-Django with MIT License | 6 votes |
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 #14
Source File: models.py From jorvik with GNU General Public License v3.0 | 6 votes |
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
Source File: dates.py From mitoc-trips with GNU General Public License v3.0 | 5 votes |
def localize(dt_time): """ Take a naive datetime and assign a time zone to it (without changing wall time). >>> from datetime import datetime >>> localize(datetime(2018, 10, 27, 4, 30) datetime.datetime(2018, 10, 27, 4, 30, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>) """ pytz_timezone = timezone.get_default_timezone() return pytz_timezone.localize(dt_time)
Example #16
Source File: test_ChangeDataVersionCommand.py From cjworkbench with GNU Affero General Public License v3.0 | 5 votes |
def _store_fetched_table(self) -> timezone.datetime: return self.wf_module.stored_objects.create(key="fake", size=10).stored_at
Example #17
Source File: test_models.py From Simple-Q-A-App-using-Python-Django with MIT License | 5 votes |
def test_affect_reputation_by_questioncomment(self): """ This test validates than the UserQAProfile method modify_reputation works properly when an QuestionComment instance is created """ other_qa_user = self.other_user.userqaprofile self.assertEqual(other_qa_user.points, 0) comment = QuestionComment.objects.create( question=self.first_question, 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, QuestionComment)) other_qa_user.refresh_from_db() self.assertEqual(other_qa_user.points, 4)
Example #18
Source File: models.py From jorvik with GNU General Public License v3.0 | 5 votes |
def persona_verifica_documenti_personali(self, persona): documents = persona.personal_identity_documents() today = datetime.datetime.now().date() gt_exists = documents.filter(expires__gt=today).exists() lt_exists = documents.filter(expires__lt=today).exists() if lt_exists and not gt_exists: return self.NON_HAI_DOCUMENTO_PERSONALE_VALIDO
Example #19
Source File: models.py From jorvik with GNU General Public License v3.0 | 5 votes |
def prossimo(self): """ Ritorna True il corso e' prossimo (inizia tra meno di due settimane). """ return ( poco_fa() <= self.data_inizio <= (poco_fa() + datetime.timedelta(15)) )
Example #20
Source File: models.py From jorvik with GNU General Public License v3.0 | 5 votes |
def pubblici(cls): """ Concept per Corsi pubblici (attivi e non ancora iniziati...) """ return Q(stato=cls.ATTIVO, data_inizio__gte=timezone.now() - datetime.timedelta( days=settings.FORMAZIONE_FINESTRA_CORSI_INIZIATI ))
Example #21
Source File: models.py From jorvik with GNU General Public License v3.0 | 5 votes |
def troppo_tardi_per_iscriverti(self): return timezone.now() > (self.data_inizio + datetime.timedelta(days=settings.FORMAZIONE_FINESTRA_CORSI_INIZIATI))
Example #22
Source File: models.py From jorvik with GNU General Public License v3.0 | 5 votes |
def corso_vecchio(self): """ Verifica se il corso appartiene al "vecchio" modulo formazione ( prima dell'aggiornamento del 31/08/2019) """ if not self.titolo_cri: return True # elif self.creazione < timezone.datetime(2019, 9, 1): # return True return False
Example #23
Source File: models.py From jorvik with GNU General Public License v3.0 | 5 votes |
def cancella_scaduti(cls): cls.objects.filter(creazione__lt=now() - datetime.timedelta(days=settings.FORMAZIONE_VALIDITA_INVITI)).delete()
Example #24
Source File: models.py From jorvik with GNU General Public License v3.0 | 5 votes |
def dividi(self): return LezioneCorsoBase.objects.create( corso=self.corso, lezione_divisa_parent=self, scheda_lezione_num=self.scheda_lezione_num, inizio=self.inizio + datetime.timedelta(minutes=60), nome=self.nome, # docente=self.docente, # luogo=self.luogo, )
Example #25
Source File: dates.py From mitoc-trips with GNU General Public License v3.0 | 5 votes |
def jan_1(): jan_1st = timezone.datetime(local_date().year, 1, 1) return localize(jan_1st)
Example #26
Source File: dates.py From mitoc-trips with GNU General Public License v3.0 | 5 votes |
def date_from_iso(datestring): """ Convert a YYYY-MM-DD datestring to a date object. Throws ValueError or TypeError on invalid inputs. """ # Might throw ValueError or TypeError moment = datetime.strptime(datestring, '%Y-%m-%d') return moment.date()
Example #27
Source File: test_save.py From cjworkbench with GNU Affero General Public License v3.0 | 5 votes |
def test_mark_result_unchanged(self, send_update): send_update.side_effect = async_noop workflow = Workflow.create_and_init() wf_module = workflow.tabs.first().wf_modules.create( order=0, slug="step-1", is_busy=True, fetch_errors=[RenderError(I18nMessage("foo", {}, "module"))], ) now = timezone.datetime(2019, 10, 22, 12, 22, tzinfo=timezone.utc) self.run_with_async_db(save.mark_result_unchanged(workflow.id, wf_module, now)) self.assertEqual(wf_module.stored_objects.count(), 0) self.assertEqual( wf_module.fetch_errors, [RenderError(I18nMessage("foo", {}, "module"))] ) self.assertEqual(wf_module.is_busy, False) self.assertEqual(wf_module.last_update_check, now) wf_module.refresh_from_db() self.assertEqual( wf_module.fetch_errors, [RenderError(I18nMessage("foo", {}, "module"))] ) self.assertEqual(wf_module.is_busy, False) self.assertEqual(wf_module.last_update_check, now) send_update.assert_called_with( workflow.id, clientside.Update( steps={ wf_module.id: clientside.StepUpdate( is_busy=False, last_fetched_at=now ) } ), )
Example #28
Source File: test_save.py From cjworkbench with GNU Affero General Public License v3.0 | 5 votes |
def test_create_result(self, send_update): send_update.side_effect = async_noop workflow = Workflow.create_and_init() wf_module = workflow.tabs.first().wf_modules.create( order=0, slug="step-1", is_busy=True, fetch_errors=[RenderError(I18nMessage("foo", {}, "module"))], ) now = timezone.datetime(2019, 10, 22, 12, 22, tzinfo=timezone.utc) with parquet_file({"A": [1], "B": ["x"]}) as parquet_path: self.run_with_async_db( save.create_result( workflow.id, wf_module, FetchResult(parquet_path), now ) ) self.assertEqual(wf_module.stored_objects.count(), 1) self.assertEqual(wf_module.fetch_errors, []) self.assertEqual(wf_module.is_busy, False) self.assertEqual(wf_module.last_update_check, now) wf_module.refresh_from_db() self.assertEqual(wf_module.fetch_errors, []) self.assertEqual(wf_module.is_busy, False) self.assertEqual(wf_module.last_update_check, now) send_update.assert_called_with( workflow.id, clientside.Update( steps={ wf_module.id: clientside.StepUpdate( is_busy=False, last_fetched_at=now ) } ), ) workflow.refresh_from_db() self.assertIsInstance(workflow.last_delta, ChangeDataVersionCommand)
Example #29
Source File: io.py From cjworkbench with GNU Affero General Public License v3.0 | 5 votes |
def create_stored_object( workflow_id: int, wf_module_id: int, path: Path, stored_at: Optional[timezone.datetime] = None, ) -> StoredObject: """ Write and return a new StoredObject. The caller should call enforce_storage_limits() after calling this. Raise IntegrityError if a database race prevents saving this. Raise a minio error if writing to minio failed. In case of partial completion, a StoredObject will exist in the database but no file will be saved in minio. """ if stored_at is None: stored_at = timezone.now() key = _build_key(workflow_id, wf_module_id) size = path.stat().st_size stored_object = StoredObject.objects.create( stored_at=stored_at, wf_module_id=wf_module_id, key=key, size=size, hash="unhashed", ) minio.fput_file(BUCKET, key, path) return stored_object
Example #30
Source File: save.py From cjworkbench with GNU Affero General Public License v3.0 | 5 votes |
def _do_mark_result_unchanged( workflow_id: int, wf_module: WfModule, now: timezone.datetime ) -> None: """ Do database manipulations for mark_result_unchanged(). Modify `wf_module` in-place. Raise WfModule.DoesNotExist or Workflow.DoesNotExist in case of a race. """ with _locked_wf_module(workflow_id, wf_module): wf_module.is_busy = False wf_module.last_update_check = now wf_module.save(update_fields=["is_busy", "last_update_check"])