當前位置: 首頁>>代碼示例>>Python>>正文


Python timezone.localtime方法代碼示例

本文整理匯總了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 
開發者ID:mvantellingen,項目名稱:django-healthchecks,代碼行數:21,代碼來源:admin.py

示例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) 
開發者ID:stormsha,項目名稱:StormOnline,代碼行數:25,代碼來源:util.py

示例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) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:23,代碼來源:tz.py

示例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 
開發者ID:City-of-Helsinki,項目名稱:linkedevents,代碼行數:23,代碼來源:test_event_post.py

示例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 
開發者ID:City-of-Helsinki,項目名稱:linkedevents,代碼行數:25,代碼來源:test_event_put.py

示例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) 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:22,代碼來源:tz.py

示例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) 
開發者ID:yunity,項目名稱:karrot-backend,代碼行數:18,代碼來源:tasks.py

示例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],
        ) 
開發者ID:yunity,項目名稱:karrot-backend,代碼行數:24,代碼來源:views.py

示例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,
        }) 
開發者ID:idaholab,項目名稱:civet,代碼行數:25,代碼來源:views.py

示例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 
開發者ID:whitesmith,項目名稱:hawkpost,代碼行數:19,代碼來源:forms.py

示例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) 
開發者ID:Superbsco,項目名稱:weibo-analysis-system,代碼行數:25,代碼來源:util.py

示例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()) 
開發者ID:wagtail,項目名稱:django-modelcluster,代碼行數:21,代碼來源:models.py

示例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,
    ) 
開發者ID:evernote,項目名稱:zing,代碼行數:22,代碼來源:invoice.py

示例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) 
開發者ID:healthchecks,項目名稱:healthchecks,代碼行數:25,代碼來源:views.py

示例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) 
開發者ID:Yeah-Kun,項目名稱:python,代碼行數:22,代碼來源:tz.py


注:本文中的django.utils.timezone.localtime方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。