本文整理汇总了Python中django.utils.timezone.datetime方法的典型用法代码示例。如果您正苦于以下问题:Python timezone.datetime方法的具体用法?Python timezone.datetime怎么用?Python timezone.datetime使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.timezone
的用法示例。
在下文中一共展示了timezone.datetime方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _dict
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import datetime [as 别名]
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
示例2: update_top_stories
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import datetime [as 别名]
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
示例3: count_active_days
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import datetime [as 别名]
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
示例4: test_first_ready
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import datetime [as 别名]
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
示例5: test_author_required_allow_object_user
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import datetime [as 别名]
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)
示例6: test_author_required_not_allow_not_object_user
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import datetime [as 别名]
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)
示例7: setUp
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import datetime [as 别名]
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,
)
示例8: test_affect_reputation_by_question
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import datetime [as 别名]
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)
示例9: test_affect_reputation_by_answer
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import datetime [as 别名]
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)
示例10: test_affect_reputation_by_answercomment
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import datetime [as 别名]
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)
示例11: build_approval_email
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import datetime [as 别名]
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]
示例12: _do_create_result
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import datetime [as 别名]
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"])
示例13: test_put_entry_dup
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import datetime [as 别名]
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
示例14: lezione_ore
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import datetime [as 别名]
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)
示例15: month
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import datetime [as 别名]
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)