本文整理汇总了Python中django.utils.timezone.localtime方法的典型用法代码示例。如果您正苦于以下问题:Python timezone.localtime方法的具体用法?Python timezone.localtime怎么用?Python timezone.localtime使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.utils.timezone
的用法示例。
在下文中一共展示了timezone.localtime方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: last_beat_column
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import localtime [as 别名]
def last_beat_column(self, object):
last_beat = object.last_beat
if is_aware(last_beat):
# Only for USE_TZ=True
last_beat = localtime(last_beat)
last_beat_str = localize(last_beat)
if object.is_expired:
# Make clearly visible
alert_icon = static('admin/img/icon-alert.svg')
return format_html(
'<div style="vertical-align: middle; display: inline-block;">'
' <img src="{}" style="vertical-align: middle;"> '
' <span style="color: #efb80b; vertical-align: middle;">{}</span>'
'</div>',
alert_icon, last_beat_str
)
else:
return last_beat_str
示例2: display_for_field
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import localtime [as 别名]
def display_for_field(value, field):
from xadmin.views.list import EMPTY_CHANGELIST_VALUE
if field.flatchoices:
return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
# NullBooleanField needs special-case null-handling, so it comes
# before the general null test.
elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
return boolean_icon(value)
elif value is None:
return EMPTY_CHANGELIST_VALUE
elif isinstance(field, models.DateTimeField):
return formats.localize(tz_localtime(value))
elif isinstance(field, (models.DateField, models.TimeField)):
return formats.localize(value)
elif isinstance(field, models.DecimalField):
return formats.number_format(value, field.decimal_places)
elif isinstance(field, models.FloatField):
return formats.number_format(value)
elif isinstance(field.rel, models.ManyToManyRel):
return ', '.join([smart_text(obj) for obj in value.all()])
else:
return smart_text(value)
示例3: localtime_tag
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import localtime [as 别名]
def localtime_tag(parser, token):
"""
Forces or prevents conversion of datetime objects to local time,
regardless of the value of ``settings.USE_TZ``.
Sample usage::
{% localtime off %}{{ value_in_utc }}{% endlocaltime %}
"""
bits = token.split_contents()
if len(bits) == 1:
use_tz = True
elif len(bits) > 2 or bits[1] not in ('on', 'off'):
raise TemplateSyntaxError("%r argument should be 'on' or 'off'" %
bits[0])
else:
use_tz = bits[1] == 'on'
nodelist = parser.parse(('endlocaltime',))
parser.delete_first_token()
return LocalTimeNode(nodelist, use_tz)
示例4: test__autopopulated_fields_at_create
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import localtime [as 别名]
def test__autopopulated_fields_at_create(
api_client, minimal_event_dict, user, user2, other_data_source, organization, organization2):
# create an event
api_client.force_authenticate(user=user)
response = create_with_post(api_client, minimal_event_dict)
event = Event.objects.get(id=response.data['id'])
assert event.created_by == user
assert event.last_modified_by == user
assert event.created_time is not None
assert event.last_modified_time is not None
assert event.data_source.id == settings.SYSTEM_DATA_SOURCE_ID
assert event.publisher == organization
# events are automatically marked as ending at midnight, local time
assert event.end_time == timezone.localtime(timezone.now() + timedelta(days=2)).\
replace(hour=0, minute=0, second=0, microsecond=0).astimezone(pytz.utc)
assert event.has_end_time is False
# the following values may not be posted
示例5: test__update_minimal_event_with_autopopulated_fields_with_put
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import localtime [as 别名]
def test__update_minimal_event_with_autopopulated_fields_with_put(api_client, minimal_event_dict, user, organization):
# create an event
api_client.force_authenticate(user=user)
response = create_with_post(api_client, minimal_event_dict)
data = response.data
assert_event_data_is_equal(minimal_event_dict, data)
event_id = data['@id']
response2 = update_with_put(api_client, event_id, minimal_event_dict)
assert_event_data_is_equal(data, response2.data)
event = Event.objects.get(id=data['id'])
assert event.created_by == user
assert event.last_modified_by == user
assert event.created_time is not None
assert event.last_modified_time is not None
assert event.data_source.id == settings.SYSTEM_DATA_SOURCE_ID
assert event.publisher == organization
# events are automatically marked as ending at midnight, local time
assert event.end_time == timezone.localtime(timezone.now() + timedelta(days=2)).\
replace(hour=0, minute=0, second=0, microsecond=0).astimezone(pytz.utc)
assert event.has_end_time is False
示例6: localtime_tag
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import localtime [as 别名]
def localtime_tag(parser, token):
"""
Force or prevent conversion of datetime objects to local time,
regardless of the value of ``settings.USE_TZ``.
Sample usage::
{% localtime off %}{{ value_in_utc }}{% endlocaltime %}
"""
bits = token.split_contents()
if len(bits) == 1:
use_tz = True
elif len(bits) > 2 or bits[1] not in ('on', 'off'):
raise TemplateSyntaxError("%r argument should be 'on' or 'off'" %
bits[0])
else:
use_tz = bits[1] == 'on'
nodelist = parser.parse(('endlocaltime',))
parser.delete_first_token()
return LocalTimeNode(nodelist, use_tz)
示例7: daily_activity_notifications
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import localtime [as 别名]
def daily_activity_notifications():
with timer() as t:
for group in Group.objects.all():
with timezone.override(group.timezone):
if timezone.localtime().hour != 20: # only at 8pm local time
continue
for data in fetch_activity_notification_data_for_group(group):
prepare_activity_notification_email(**data).send()
stats.activity_notification_email(
group=data['group'], **{k: v.count()
for k, v in data.items() if isinstance(v, QuerySet)}
)
stats_utils.periodic_task('activities__daily_activity_notifications', seconds=t.elapsed_seconds)
示例8: activity_notification
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import localtime [as 别名]
def activity_notification(self):
user = random_user()
activity1 = Activity.objects.order_by('?').first()
activity2 = Activity.objects.order_by('?').first()
activity3 = Activity.objects.order_by('?').first()
activity4 = Activity.objects.order_by('?').first()
localtime = timezone.localtime()
return prepare_activity_notification_email(
user=user,
group=user.groups.first(),
tonight_date=localtime,
tomorrow_date=localtime + relativedelta(days=1),
tonight_user=[activity1, activity2],
tonight_empty=[activity3, activity4],
tonight_not_full=[activity4],
tomorrow_user=[activity2],
tomorrow_empty=[activity3],
tomorrow_not_full=[activity4],
)
示例9: main_update
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import localtime [as 别名]
def main_update(request):
"""
Get the updates for the main page.
"""
if 'last_request' not in request.GET or 'limit' not in request.GET:
return HttpResponseBadRequest('Missing parameters')
this_request = TimeUtils.get_local_timestamp()
limit = int(request.GET['limit'])
last_request = int(float(request.GET['last_request'])) # in case it has decimals
dt = timezone.localtime(timezone.make_aware(datetime.datetime.utcfromtimestamp(last_request)))
repos_data, einfo, default = views.get_user_repos_info(request, limit=limit, last_modified=dt)
# we also need to check if a PR closed recently
closed = []
for pr in models.PullRequest.objects.filter(closed=True, last_modified__gte=dt).values('id').all():
closed.append({'id': pr['id']})
return JsonResponse({'repo_status': repos_data,
'closed': closed,
'last_request': this_request,
'events': einfo,
'limit': limit,
})
示例10: clean_expires_at
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import localtime [as 别名]
def clean_expires_at(self):
# Validate the expiration date
expires_at = self.cleaned_data.get("expires_at", "")
never_expires = self.cleaned_data.get("never_expires", "")
current_tz = timezone.get_current_timezone()
if never_expires:
expires_at = None
self.cleaned_data["expires_at"] = expires_at
if expires_at:
# Check if the expiration date is a past date
if timezone.localtime(timezone.now(), current_tz) > expires_at:
self.add_error('expires_at', _('The date must be on the future.'))
if not expires_at and not never_expires:
self.add_error('expires_at',
_('This field is required, unless box is set to '
'never expire.'))
return expires_at
示例11: display_for_field
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import localtime [as 别名]
def display_for_field(value, field):
from xadmin.views.list import EMPTY_CHANGELIST_VALUE
if field.flatchoices:
return dict(field.flatchoices).get(value, EMPTY_CHANGELIST_VALUE)
# NullBooleanField needs special-case null-handling, so it comes
# before the general null test.
elif isinstance(field, models.BooleanField) or isinstance(field, models.NullBooleanField):
return boolean_icon(value)
elif value is None:
return EMPTY_CHANGELIST_VALUE
elif isinstance(field, models.DateTimeField):
return formats.localize(tz_localtime(value))
elif isinstance(field, (models.DateField, models.TimeField)):
return formats.localize(value)
elif isinstance(field, models.DecimalField):
return formats.number_format(value, field.decimal_places)
elif isinstance(field, models.FloatField):
return formats.number_format(value)
elif isinstance(field.remote_field, models.ManyToManyRel):
return ', '.join([smart_text(obj) for obj in value.all()])
else:
return smart_text(value)
示例12: get_field_value
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import localtime [as 别名]
def get_field_value(field, model):
if field.remote_field is None:
value = field.pre_save(model, add=model.pk is None)
# Make datetimes timezone aware
# https://github.com/django/django/blob/master/django/db/models/fields/__init__.py#L1394-L1403
if isinstance(value, datetime.datetime) and settings.USE_TZ:
if timezone.is_naive(value):
default_timezone = timezone.get_default_timezone()
value = timezone.make_aware(value, default_timezone).astimezone(timezone.utc)
# convert to UTC
value = timezone.localtime(value, timezone.utc)
if is_protected_type(value):
return value
else:
return field.value_to_string(model)
else:
return getattr(model, field.get_attname())
示例13: _check_single_paidtask
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import localtime [as 别名]
def _check_single_paidtask(invoice, amount):
server_tz = timezone.get_default_timezone()
local_now = timezone.localtime(invoice.now, server_tz)
current_month_start = local_now.replace(
day=1, hour=0, minute=0, second=0, microsecond=0
)
PaidTask.objects.get(
task_type=PaidTaskTypes.CORRECTION,
amount=(-1) * amount,
datetime=invoice.month_end,
description="Carryover to the next month",
user=invoice.user,
)
PaidTask.objects.get(
task_type=PaidTaskTypes.CORRECTION,
amount=amount,
datetime=current_month_start,
description="Carryover from the previous month",
user=invoice.user,
)
示例14: cron_preview
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import localtime [as 别名]
def cron_preview(request):
schedule = request.POST.get("schedule", "")
tz = request.POST.get("tz")
ctx = {"tz": tz, "dates": []}
try:
zone = pytz.timezone(tz)
now_local = timezone.localtime(timezone.now(), zone)
if len(schedule.split()) != 5:
raise ValueError()
it = croniter(schedule, now_local)
for i in range(0, 6):
ctx["dates"].append(it.get_next(datetime))
ctx["desc"] = str(ExpressionDescriptor(schedule, use_24hour_time_format=True))
except UnknownTimeZoneError:
ctx["bad_tz"] = True
except:
ctx["bad_schedule"] = True
return render(request, "front/cron_preview.html", ctx)
示例15: localtime_tag
# 需要导入模块: from django.utils import timezone [as 别名]
# 或者: from django.utils.timezone import localtime [as 别名]
def localtime_tag(parser, token):
"""
Forces or prevents conversion of datetime objects to local time,
regardless of the value of ``settings.USE_TZ``.
Sample usage::
{% localtime off %}{{ value_in_utc }}{% endlocaltime %}
"""
bits = token.split_contents()
if len(bits) == 1:
use_tz = True
elif len(bits) > 2 or bits[1] not in ('on', 'off'):
raise TemplateSyntaxError("%r argument should be 'on' or 'off'" %
bits[0])
else:
use_tz = bits[1] == 'on'
nodelist = parser.parse(('endlocaltime',))
parser.delete_first_token()
return LocalTimeNode(nodelist, use_tz)