本文整理汇总了Python中django.utils.timezone.now方法的典型用法代码示例。如果您正苦于以下问题:Python timezone.now方法的具体用法?Python timezone.now怎么用?Python timezone.now使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.timezone
的用法示例。
在下文中一共展示了timezone.now方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: register
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import now [as 别名]
def register(request):
"""
New user applying for access
"""
form = RegistrationForm()
data = {'title': _("Register")}
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User(is_active=False)
user.email = form.cleaned_data['email']
user.last_name = form.cleaned_data['last_name']
user.first_name = form.cleaned_data['first_name']
user.set_password(form.cleaned_data['password'])
user.save()
messages.success(request, _(u'Your registration is now pending approval.'))
return redirect(login)
data['form'] = form
return render(request, 'accounts/register.html', data)
示例2: close
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import now [as 别名]
def close(self, user):
"""Close this service order."""
if Configuration.autocomplete_repairs():
for r in self.repair_set.active():
try:
r.set_status_code('RFPU')
r.close(user)
except Exception as e:
# notify the creator of the GSX repair instead of just erroring out
e = self.notify("gsx_error", e, user)
e.notify_users.add(r.created_by)
if self.queue and self.queue.status_closed:
self.set_status(self.queue.status_closed, user)
self.notify("close_order", _(u"Order %s closed") % self.code, user)
self.closed_by = user
self.closed_at = timezone.now()
self.state = self.STATE_CLOSED
self.save()
示例3: submit
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import now [as 别名]
def submit(self):
esc = self.to_gsx()
esc.shipTo = self.gsx_account.ship_to
esc.issueTypeCode = self.issue_type
if len(self.contexts) > 2:
ec = []
for k, v in json.loads(self.contexts).items():
ec.append(Context(k, v))
esc.escalationContext = ec
result = esc.create()
self.submitted_at = timezone.now()
self.escalation_id = result.escalationId
self.save()
示例4: create
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import now [as 别名]
def create(self, validated_data):
now = timezone.now()
user = User(
email=validated_data.get('email'),
username=validated_data.get('username'),
last_login=now,
date_joined=now,
is_active=True
)
if validated_data.get('first_name'):
user.first_name = validated_data['first_name']
if validated_data.get('last_name'):
user.last_name = validated_data['last_name']
user.set_password(validated_data['password'])
# Make the first signup an admin / superuser
if not User.objects.filter(is_superuser=True).exists():
user.is_superuser = user.is_staff = True
user.save()
return user
示例5: handle
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import now [as 别名]
def handle(self, *args, **kwargs):
with open('polls/fixtures/initial_data.json') as fp:
initial_data = json.load(fp)
initial_questions = filter(lambda m: m['model'] == 'polls.question', initial_data)
initial_question_pks = map(lambda m: m['pk'], initial_questions)
one_hour_ago = timezone.now() - timedelta(hours=1)
qs = Question.objects.exclude(id__in=initial_question_pks).filter(published_at__lt=one_hour_ago)
print('Deleting {} questions'.format(qs.count()))
qs.delete()
qa = Vote.objects.all()
print('Deleting {} votes'.format(qs.count()))
qs.delete()
示例6: test_latest_by
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import now [as 别名]
def test_latest_by(self):
# set up observations going backward in time
sample_time = timezone.now()
for ihour in range(10):
Attribute.objects.create(
valid_at=sample_time-timedelta(hours=ihour),
value=ihour*0.5,
units='kW',
device=self.device,
)
# get latest and earliest
latest = Attribute.objects.latest()
earliest = Attribute.objects.earliest()
# latest should have later valid_at but earlier created_at
self.assertGreater(latest.valid_at, earliest.valid_at)
self.assertLess(latest.created_at, earliest.created_at)
示例7: smartdate
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import now [as 别名]
def smartdate(value):
if isinstance(value, datetime.datetime):
now = django_now()
else:
now = datetime.date.today()
timedelta = value - now
format = _(u"%(delta)s %(unit)s")
delta = abs(timedelta.days)
if delta > 30:
delta = int(delta / 30)
unit = _(u"mois")
else:
unit = _(u"jours")
ctx = {
'delta': delta,
'unit': unit,
}
return format % ctx
示例8: check_date_dued
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import now [as 别名]
def check_date_dued(self, check):
if self.date_dued is None:
check.mark_fail(message="No due date specified")
return check
if self.total_excl_tax == D('0'):
check.mark_fail(message="The invoice has no value")
return check
if self.is_fully_paid():
last_payment = self.payments.all().first()
formatted_date = last_payment.date_paid.strftime('%B %d, %Y')
check.mark_pass(message="Has been paid on the {}"
.format(formatted_date))
return check
if timezone.now().date() > self.date_dued:
check.mark_fail(message="The due date has been exceeded.")
else:
check.mark_pass()
return check
示例9: get_initial
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import now [as 别名]
def get_initial(self):
initial = super().get_initial()
# currrent quarter
now = timezone.now()
start = date(
year=now.year,
month=(now.month - ((now.month - 1) % 3)),
day=1
)
end = start + relativedelta(months=3)
initial['date_from'] = start
initial['date_to'] = end
return initial
示例10: get_context_data
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import now [as 别名]
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
orga = organization_manager.get_selected_organization(self.request)
# currrent quarter
now = timezone.now()
start = date(
year=now.year,
month=(now.month - ((now.month - 1) % 3)),
day=1
)
end = start + relativedelta(months=3)
report = ProfitAndLossReport(orga, start=start, end=end)
report.generate()
ctx['summaries'] = report.summaries
ctx['total_summary'] = report.total_summary
return ctx
示例11: _create_user
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import now [as 别名]
def _create_user(self, email, password,
is_staff, is_superuser, **extra_fields):
"""
Creates and saves a User with the given username, email and password.
"""
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email,
is_staff=is_staff, is_active=True,
is_superuser=is_superuser,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
示例12: _update
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import now [as 别名]
def _update(cls, name, default_timeout=None, timeout=None):
"""Internal function to update a heartbeat.
Use :func:`django_healthchecks.heartbeats.update_heartbeat` instead.
"""
extra_updates = {}
if timeout is not None:
extra_updates['timeout'] = timeout
rows = cls.objects.filter(name=name).update(last_beat=now(), **extra_updates)
if not rows:
return cls.objects.create(
name=name,
enabled=True,
timeout=timeout or default_timeout or _get_default_timeout(),
last_beat=now(),
)
示例13: check_validity
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import now [as 别名]
def check_validity(not_before, not_after, expire_early):
"""
Check validity dates.
If not_before is in the past, and not_after is in the future,
return True, otherwise raise an Exception explaining the problem.
If expire_early is passed, an exception will be raised if the
not_after date is too soon in the future.
"""
now = datetime.utcnow().replace(tzinfo=pytz.utc)
if not_before > not_after:
raise BadCertificate(f"not_before ({not_before}) after not_after ({not_after})")
if now < not_before:
raise CertificateNotYetValid(not_before)
if now > not_after:
raise CertificateExpired(not_after)
if expire_early:
if now + expire_early > not_after:
raise CertificateExpiringSoon(expire_early)
return True
示例14: handle
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import now [as 别名]
def handle(self, *args, **options):
"""Handle the command invocation."""
if options['frequency'] == 'daily':
self.report(send_digest_emails(DigestFrequency.daily))
elif options['frequency'] == 'weekly':
digest_day = getattr(settings, 'DIGEST_WEEKLY_DAY')
current_day = timezone.now().weekday()
if current_day == digest_day or options['force']:
if current_day != digest_day and options['force']:
msg = 'Forcing weekly digest to be sent (scheduled=%s, current=%s)' % (digest_day, current_day)
self.stdout.write(self.style.WARNING(msg)) # pylint: disable=no-member
self.report(send_digest_emails(DigestFrequency.weekly))
else:
msg = 'Skipping weekly digest until day %s (current=%s)' % (digest_day, current_day)
self.stdout.write(self.style.WARNING(msg)) # pylint: disable=no-member
else:
raise CommandError('Expected frequency "daily" or "weekly"')
示例15: touch
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import now [as 别名]
def touch(self, user, commit=True):
self.modified = timezone.now()
self.modified_by = user
if commit:
if self.parent:
self.parent.touch(user)
self.save()