Python django.utils.timezone 模块,localtime() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.timezone.localtime()

项目:mccelections    作者:mcclatchy    | 项目源码 | 文件源码
def handle(self, *args, **options):
        electiondate_arg = options['electiondate']
        model_arg = options['model']

        start_time = timezone.localtime(timezone.now())

        start_message = '\nStarted baking:\t\t' + str(unicode(start_time)) + '\n'

        message = start_message
        slackbot(message)

        bake_api_to_static(electiondate_arg, model_arg)

        end_time = timezone.localtime(timezone.now())

        end_message = '\nFinished baking:\t' + str(unicode(end_time)) + '\n\n'
        bake_length = str(unicode(end_time - start_time)) 

        message = end_message
        slackbot(message)

        message = 'Bake length:\t\t' + bake_length
        slackbot(message)
        message = '--------------------------------------------------\n'
        slackbot(message)
项目:mccelections    作者:mcclatchy    | 项目源码 | 文件源码
def handle(self, *args, **options):
        electiondate_arg = options['electiondate']
        model_arg = options['model']

        start_time = timezone.localtime(timezone.now())

        start_message = '\nStarted generating:\t\t' + str(unicode(start_time)) + '\n'

        message = start_message
        slackbot(message)

        generate_json(electiondate_arg, model_arg)

        end_time = timezone.localtime(timezone.now())

        end_message = '\nFinished generating:\t\t' + str(unicode(end_time)) + '\n\n'
        generate_length = str(unicode(end_time - start_time)) 

        message = end_message
        slackbot(message)

        message = 'Generate length:\t\t' + generate_length
        slackbot(message)
        message = '--------------------------------------------------\n'
        slackbot(message)
项目:zing    作者:evernote    | 项目源码 | 文件源码
def _check_single_paidtask(invoice, amount):
    local_now = timezone.localtime(invoice.now)
    current_month_start = local_now.replace(day=1, hour=0, minute=0, second=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,
    )
    assert PaidTask.objects.filter(task_type=PaidTaskTypes.CORRECTION).count() == 2
项目:zing    作者:evernote    | 项目源码 | 文件源码
def _add_correction(self, total_amount):
        """Adds a correction for the value of `total_amount` in the month being
        processed.
        """
        server_tz = timezone.get_default_timezone()
        local_now = timezone.localtime(self.now, server_tz)
        initial_moment = local_now.replace(day=1, hour=0, minute=0, second=0)

        PaidTask.objects.get_or_create(
            task_type=PaidTaskTypes.CORRECTION,
            amount=(-1) * total_amount,
            rate=1,
            datetime=self.month_end,
            description='Carryover to the next month',
            user=self.user,
        )
        PaidTask.objects.get_or_create(
            task_type=PaidTaskTypes.CORRECTION,
            amount=total_amount,
            rate=1,
            datetime=initial_moment,
            description='Carryover from the previous month',
            user=self.user,
        )
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        context = super(LCTimeslotQuestionsView, self
                        ).get_context_data(**kwargs)
        tsid = context.get('tsid')
        lc_timeslot = models.LiveCourseTimeSlot.objects.filter(pk=tsid).first()
        context['lc_timeslot'] = lc_timeslot
        if not lc_timeslot:
            context['error_msg'] = "??????"
            return context
        lecturer = self.get_lecturer()
        lc = lc_timeslot.live_course
        context['course_name'] = lc.name
        context['lecturer_name'] = lc.lecturer.name
        context['date'] = timezone.localtime(
            lc_timeslot.start).strftime('%Y-%m-%d')
        context['start'] = timezone.localtime(
            lc_timeslot.start).strftime('%H:%M')
        context['end'] = timezone.localtime(
            lc_timeslot.end).strftime('%H:%M')
        old_groups = lc_timeslot.question_groups.filter(deleted=False)
        context['old_groups'] = old_groups
        return context
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def test_orders_timeslots(self):
        def weekly_2_mins(weekly):
            return ((weekly.weekday - 1) * 24 * 60 + weekly.start.hour * 60 +
                    weekly.start.minute, (weekly.weekday - 1) * 24 * 60 +
                    weekly.end.hour * 60 + weekly.end.minute)

        orders = Order.objects.filter(status='p')
        for order in orders:
            timeslots = order.timeslot_set.filter(deleted=False)
            weekly_time_slots = order.weekly_time_slots.all()
            mins = [weekly_2_mins(x) for x in weekly_time_slots]
            for timeslot in timeslots:
                timeslot.start = timezone.localtime(timeslot.start)
                timeslot.end = timezone.localtime(timeslot.end)
                cur_min = (
                        timeslot.start.weekday() * 24 * 60 +
                        timeslot.start.hour * 60 + timeslot.start.minute,
                        timeslot.end.weekday() * 24 * 60 +
                        timeslot.end.hour * 60 + timeslot.end.minute)
                self.assertIn(cur_min, mins)
项目:Server    作者:malaonline    | 项目源码 | 文件源码
def __call__(self, time_slot: models.TimeSlot):
            if time_slot.is_complete() and hasattr(time_slot, "comment"):
                comment = time_slot.comment
                if comment:
                    self.count_comment(comment)
                    if self.is_valid(comment):
                        if self.cres.is_error and self.cres.id == time_slot.comment_id:
                            the_form = forms.CommentReplyForm(initial={"reply": self.cres.reply})
                        else:
                            the_form = forms.CommentReplyForm()
                        one_comment = {
                            "name": self.name,
                            "publish_date": localtime(comment.created_at).strftime("%Y-%m-%d %H:%M"),
                            "full_star": range(comment.score),
                            "empty_star": range(5 - comment.score),
                            "comment": comment.content,
                            "class_type": self.class_type + "1?1",
                            "form": the_form,
                            "action_url": "reply/comment/{id}".format(id=comment.id),
                            "form_id": "reply_form_{id}".format(id=comment.id),
                            "reply_id": "reply_{id}".format(id=comment.id),
                            "reply_content": comment.reply
                        }
                        self.comment_list.append(one_comment)
项目:blog_django    作者:chnpmy    | 项目源码 | 文件源码
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)
项目:dream_blog    作者:fanlion    | 项目源码 | 文件源码
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)
项目:Ares    作者:tehpug    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        """
        Manipulating template context 
        """
        ctx = super(LeagueDetail, self).get_context_data(**kwargs)
        now = timezone.localtime()
        ctx['is_registered'] = False
        ctx['is_expired'] = False
        ctx['is_full'] = self.object.robots.count() == self.object.num_robots
        if self.request.user.is_authenticated():
            ctx['is_registered'] = self.object.robots.filter(
                user=self.request.user).count() > 0
        if now > self.object.registration_end or \
                now < self.object.registration_start:
            ctx['is_expired'] = True

        if ctx['is_expired']:
            ctx['table'] = League.get_table()

        return ctx
项目:MxOnline    作者:myTeemo    | 项目源码 | 文件源码
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_unicode(obj) for obj in value.all()])
    else:
        return smart_unicode(value)
项目:djangoblog    作者:liuhuipy    | 项目源码 | 文件源码
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)
项目:PonyConf    作者:PonyConf    | 项目源码 | 文件源码
def _add_talk(self, talk):
        room = talk.room
        dt1 = talk.start_date
        d1 = localtime(dt1).date()
        dt2 = talk.start_date + timedelta(minutes=talk.estimated_duration)
        d2 = localtime(dt2).date()
        assert(d1 == d2) # this is a current limitation
        dt1 = self.days[d1]['timeslots'].index(dt1)
        dt2 = self.days[d1]['timeslots'].index(dt2)
        col = None
        for row, timeslot in enumerate(islice(self.days[d1]['timeslots'], dt1, dt2)):
            if col is None:
                col = 0
                while col < len(self.days[d1]['rows'][timeslot][room]) and self.days[d1]['rows'][timeslot][room][col]:
                    col += 1
                self.cols[room] = max(self.cols[room], col+1)
            event = Event(talk=talk, row=row, rowcount=dt2-dt1)
            while len(self.days[d1]['rows'][timeslot][room]) <= col:
                self.days[d1]['rows'][timeslot][room].append(None)
            self.days[d1]['rows'][timeslot][room][col] = event
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
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)
项目:isar    作者:ilbers    | 项目源码 | 文件源码
def _modify_date_range_filter(filter_string):
    # was the date range radio button selected?
    if 0 >  filter_string.find('_daterange'):
        return filter_string,''
    # normalize GUI dates to database format
    filter_string = filter_string.replace('_daterange','').replace(':','!');
    filter_list = filter_string.split('!');
    if 4 != len(filter_list):
        return filter_string
    today = timezone.localtime(timezone.now())
    date_id = filter_list[1]
    date_from = _normalize_input_date(filter_list[2],today)
    date_to = _normalize_input_date(filter_list[3],today)
    # swap dates if manually set dates are out of order
    if  date_to < date_from:
        date_to,date_from = date_from,date_to
    # convert to strings, make 'date_to' inclusive by moving to begining of next day
    date_from_str = date_from.strftime("%Y-%m-%d")
    date_to_str = (date_to+timedelta(days=1)).strftime("%Y-%m-%d")
    filter_string=filter_list[0]+'!'+filter_list[1]+':'+date_from_str+'!'+date_to_str
    daterange_selected = re.sub('__.*','', date_id)
    return filter_string,daterange_selected
项目:DjangoBlog    作者:0daybug    | 项目源码 | 文件源码
def _sqlite_datetime_trunc(lookup_type, dt, tzname):
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if tzname is not None:
        dt = timezone.localtime(dt, pytz.timezone(tzname))
    if lookup_type == 'year':
        return "%i-01-01 00:00:00" % dt.year
    elif lookup_type == 'month':
        return "%i-%02i-01 00:00:00" % (dt.year, dt.month)
    elif lookup_type == 'day':
        return "%i-%02i-%02i 00:00:00" % (dt.year, dt.month, dt.day)
    elif lookup_type == 'hour':
        return "%i-%02i-%02i %02i:00:00" % (dt.year, dt.month, dt.day, dt.hour)
    elif lookup_type == 'minute':
        return "%i-%02i-%02i %02i:%02i:00" % (dt.year, dt.month, dt.day, dt.hour, dt.minute)
    elif lookup_type == 'second':
        return "%i-%02i-%02i %02i:%02i:%02i" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
项目:xadmin-markdown-editor    作者:bluenknight    | 项目源码 | 文件源码
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_unicode(obj) for obj in value.all()])
    else:
        return smart_unicode(value)
项目:ecs    作者:ecs-org    | 项目源码 | 文件源码
def send_expedited_reviewer_invitations(request, meeting_pk=None):
    meeting = get_object_or_404(Meeting, pk=meeting_pk)

    categories = MedicalCategory.objects.filter(
        submissions__in=meeting.submissions.expedited())
    users = User.objects.filter(profile__is_board_member=True,
        medical_categories__in=categories.values('pk'))
    start = meeting.deadline_expedited_review
    for user in users:
        subject = _('Expedited Review at {}').format(
            timezone.localtime(start).strftime('%d.%m.%Y'))
        send_system_message_template(user, subject,
            'meetings/messages/expedited_reviewer_invitation.txt',
            {'start': start})

    meeting.expedited_reviewer_invitation_sent_at = timezone.now()
    meeting.save(update_fields=('expedited_reviewer_invitation_sent_at',))

    return redirect('ecs.meetings.views.meeting_details', meeting_pk=meeting.pk)
项目:django-danceschool    作者:django-danceschool    | 项目源码 | 文件源码
def __init__(self,object,**kwargs):

        timeZone = pytz.timezone(getattr(settings,'TIME_ZONE','UTC'))
        if kwargs.get('timeZone',None):
            try:
                timeZone = pytz.timezone(kwargs.get('timeZone',None))
            except pytz.exceptions.UnknownTimeZoneError:
                pass

        self.id = 'event_' + str(object.event.id) + '_' + str(object.id)
        self.type = 'event'
        self.id_number = object.event.id
        self.title = object.event.name
        self.description = object.event.description
        self.start = timezone.localtime(object.startTime,timeZone) \
            if timezone.is_aware(object.startTime) else object.startTime
        self.end = timezone.localtime(object.endTime,timeZone) \
            if timezone.is_aware(object.endTime) else object.endTime
        self.color = object.event.displayColor
        self.url = object.event.get_absolute_url()
        if hasattr(object,'event.location'):
            self.location = object.event.location.name + '\n' + object.event.location.address + '\n' + object.event.location.city + ', ' + object.event.location.state + ' ' + object.event.location.zip
        else:
            self.location = None
项目:trydjango18    作者:wei0104    | 项目源码 | 文件源码
def _sqlite_datetime_trunc(lookup_type, dt, tzname):
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if tzname is not None:
        dt = timezone.localtime(dt, pytz.timezone(tzname))
    if lookup_type == 'year':
        return "%i-01-01 00:00:00" % dt.year
    elif lookup_type == 'month':
        return "%i-%02i-01 00:00:00" % (dt.year, dt.month)
    elif lookup_type == 'day':
        return "%i-%02i-%02i 00:00:00" % (dt.year, dt.month, dt.day)
    elif lookup_type == 'hour':
        return "%i-%02i-%02i %02i:00:00" % (dt.year, dt.month, dt.day, dt.hour)
    elif lookup_type == 'minute':
        return "%i-%02i-%02i %02i:%02i:00" % (dt.year, dt.month, dt.day, dt.hour, dt.minute)
    elif lookup_type == 'second':
        return "%i-%02i-%02i %02i:%02i:%02i" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
项目:hawkpost    作者:whitesmith    | 项目源码 | 文件源码
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
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
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)
项目:moore    作者:UTNkar    | 项目源码 | 文件源码
def queryset(self, request, queryset):
        now = timezone.now()
        # When time zone support is enabled, convert "now" to the user's time
        # zone so Django's definition of "Today" matches what the user expects.
        if timezone.is_aware(now):
            now = timezone.localtime(now)

        this_year = now.replace(
            month=1, day=1, hour=0, minute=0, second=0, microsecond=0
        )
        next_year = date(year=this_year.year + 1, month=1, day=1)
        last_year = date(year=this_year.year - 1, month=1, day=1)

        if self.value() == 'this':
            return queryset.filter(
                term_from__gte=this_year,
                term_from__lt=next_year
            )
        elif self.value() == 'last':
            return queryset.filter(
                term_from__gte=last_year,
                term_from__lt=this_year
            )
        elif self.value() == 'before':
            return queryset.filter(term_from__lt=last_year)
项目:eduDjango    作者:yuzhou6    | 项目源码 | 文件源码
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_unicode(obj) for obj in value.all()])
    else:
        return smart_unicode(value)
项目:Django-IMOOC-Shop    作者:LBruse    | 项目源码 | 文件源码
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_unicode(obj) for obj in value.all()])
    else:
        return smart_unicode(value)
项目:StudyOnline    作者:yipwinghong    | 项目源码 | 文件源码
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_unicode(obj) for obj in value.all()])
    else:
        return smart_unicode(value)
项目:xadmin_python3    作者:mahongquan    | 项目源码 | 文件源码
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_unicode(obj) for obj in value.all()])
    else:
        return value#smart_unicode(value)
项目:supervisoradmin    作者:jimmy201602    | 项目源码 | 文件源码
def get(self,request,node_name, process_name):
        if request.session['usertype'] == 0 or request.session['usertype'] == 1:
            try:
                node_config = Config(CONFIG_FILE).getNodeConfig(node_name)
                node = Node(node_config)
                if node.connection.supervisor.stopProcess(process_name):
                    if node.connection.supervisor.startProcess(process_name):
                        add_log = open(ACTIVITY_LOG, "a")
                        add_log.write("%s - %s restarted %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
                        return JsonValue(process_name, node_name, "restart").success()
            except xmlrpclib.Fault as err:
                add_log = open(ACTIVITY_LOG, "a")
                add_log.write("%s - %s unsucces restart event %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
                return JsonValue(process_name, node_name, "restart").error(err.faultCode, err.faultString)
        else:
            add_log = open(ACTIVITY_LOG, "a")
            add_log.write("%s - %s is unauthorized user request for restart. Restart event fail for %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
            return jsonify(status = "error2",
                           message = "You are not authorized this action" )

# Process start
项目:supervisoradmin    作者:jimmy201602    | 项目源码 | 文件源码
def get(self,request,node_name, process_name):
        if request.session['usertype'] == 0 or request.session['usertype'] == 1:
            try:
                node_config = Config(CONFIG_FILE).getNodeConfig(node_name)
                node = Node(node_config)
                if node.connection.supervisor.startProcess(process_name):
                    add_log = open(ACTIVITY_LOG, "a")
                    add_log.write("%s - %s started %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
                    return JsonValue(process_name, node_name, "start").success()
            except xmlrpclib.Fault as err:
                add_log = open(ACTIVITY_LOG, "a")
                add_log.write("%s - %s unsucces start event %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
                return JsonValue(process_name, node_name, "start").error(err.faultCode, err.faultString)
        else:   
            add_log = open(ACTIVITY_LOG, "a")
            add_log.write("%s - %s is unauthorized user request for start. Start event fail for %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
            return JsonResponse({'status' : "error2",
                           'message' : "You are not authorized this action"} )


# Process stop
项目:supervisoradmin    作者:jimmy201602    | 项目源码 | 文件源码
def get(self,request,node_name, process_name):
        if request.session['usertype'] == 0 or request.session['usertype'] == 1:
            try:
                node_config = Config(CONFIG_FILE).getNodeConfig(node_name)
                node = Node(node_config)
                if node.connection.supervisor.stopProcess(process_name):
                    add_log = open(ACTIVITY_LOG, "a")
                    add_log.write("%s - %s stopped %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
                    return JsonValue(process_name, node_name, "stop").success()
            except xmlrpclib.Fault as err:
                add_log = open(ACTIVITY_LOG, "a")
                add_log.write("%s - %s unsucces stop event %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
                return JsonValue(process_name, node_name, "stop").error(err.faultCode, err.faultString)
        else:
            add_log = open(ACTIVITY_LOG, "a")
            add_log.write("%s - %s is unauthorized user request for stop. Stop event fail for %s node's %s process .\n"%( timezone.localtime().ctime(), request.session['username'], node_name, process_name ))
            return JsonResponse({'status' : "error2",
                           'message' : "You are not authorized this action"} )

# Node name list in the configuration file
项目:Django    作者:englam    | 项目源码 | 文件源码
def comment(request,id):
    if id:
        r = Restaurant.objects.get(id=id)
    else:
        return HttpResponseRedirect("/restaurants_list/")

    if request.POST:
        visitor = request.POST['visitor']
        content = request.POST['content']
        email   = request.POST['email']
        date_time = timezone.localtime(timezone.now())
        #??for database
        Comment.objects.create(
            visitor = visitor,
            email   = email,
            content = content,
            date_time  = date_time,
            restaurant = r
        )

    return render_to_response('comments.html',RequestContext(request,locals()))
项目:Django    作者:englam    | 项目源码 | 文件源码
def comment(request,id):
    if id:
        r = Restaurant.objects.get(id=id)
    else:
        return HttpResponseRedirect("/restaurants_list/")

    if request.POST:
        visitor = request.POST['visitor']
        content = request.POST['content']
        email   = request.POST['email']
        date_time = timezone.localtime(timezone.now())
        #??for database
        Comment.objects.create(
            visitor = visitor,
            email   = email,
            content = content,
            date_time  = date_time,
            restaurant = r
        )

    return render_to_response('comments.html',RequestContext(request,locals()))
项目:a4-meinberlin    作者:liqd    | 项目源码 | 文件源码
def html_date(value, displayfmt=None, datetimefmt='c', **kwargs):
    """Format a date and wrap it in a html <time> element.

    Additional html attributes may be provided as kwargs (e.g. 'class').

    Note: Converts the value to localtime as we loose the expects_localtime
    flag functionality by directly calling the date filter from django.
    """
    localtime_value = timezone.localtime(value)
    displaydate = defaultfilters.date(localtime_value, displayfmt)
    datetime = defaultfilters.date(localtime_value, datetimefmt)
    attribs = flatatt(kwargs)
    result = '<time %s datetime="%s">%s</time>' % (attribs,
                                                   datetime,
                                                   displaydate)
    return mark_safe(result)
项目:dsmr-reader    作者:dennissiemensma    | 项目源码 | 文件源码
def test_set_next_notification_date(self, now_mock):
        """ Notifications: Test if next notification date is set """
        now_mock.return_value = timezone.make_aware(
            timezone.datetime(2016, 11, 16))

        now = timezone.localtime(timezone.now())
        tomorrow = (timezone.localtime(timezone.now()) +
                    timezone.timedelta(hours=24)).date()

        settings = NotificationSetting.get_solo()
        settings.next_notification = now
        settings.save()

        dsmr_notification.services.set_next_notification(settings, now)

        self.assertEqual(settings.next_notification, tomorrow)
项目:dsmr-reader    作者:dennissiemensma    | 项目源码 | 文件源码
def test_notification_api_fail(self, now_mock, requests_post_mock):
        """ Notifications: Test API failure for notify() """
        now_mock.return_value = timezone.make_aware(
            timezone.datetime(2016, 11, 17, hour=0, minute=5))
        requests_post_mock.return_value = mock.MagicMock(
            status_code=403, text='Forbidden')

        settings = NotificationSetting.get_solo()
        settings.send_notification = True
        settings.notification_service = NotificationSetting.NOTIFICATION_NMA
        settings.api_key = 'es7sh2d-DSMR-Reader-Rulez-iweu732'
        settings.next_notification = timezone.localtime(timezone.now())
        settings.save()

        if self.fixtures:
            with self.assertRaises(AssertionError):
                dsmr_notification.services.notify()
        else:
            # When having no data, this should NOT raise an exception.
            return dsmr_notification.services.notify()

        with self.assertRaisesMessage(
                AssertionError, 'Notify API call failed: Forbidden (HTTP403)'):
            dsmr_notification.services.notify()
项目:dsmr-reader    作者:dennissiemensma    | 项目源码 | 文件源码
def test_check_interval_restriction(self, now_mock, create_backup_mock):
        """ Test whether backups are restricted by one backup per day. """
        now_mock.return_value = timezone.make_aware(timezone.datetime(2016, 1, 1, hour=1, minute=5))

        # Fake latest backup.
        now = timezone.localtime(timezone.now())
        backup_settings = BackupSettings.get_solo()
        backup_settings.latest_backup = now
        backup_settings.backup_time = (now - timezone.timedelta(minutes=1)).time()
        backup_settings.save()

        self.assertIsNotNone(BackupSettings.get_solo().latest_backup)
        self.assertFalse(create_backup_mock.called)

        # Should not do anything.
        dsmr_backup.services.backup.check()
        self.assertFalse(create_backup_mock.called)

        backup_settings.latest_backup = now - timezone.timedelta(days=1)
        backup_settings.save()

        # Should be fine to backup now.
        dsmr_backup.services.backup.check()
        self.assertTrue(create_backup_mock.called)
项目:dsmr-reader    作者:dennissiemensma    | 项目源码 | 文件源码
def test_check_backup_time_restriction(self, now_mock, create_backup_mock):
        """ Test whether backups are restricted by user's backup time preference. """
        now_mock.return_value = timezone.make_aware(timezone.datetime(2016, 1, 1, hour=1, minute=5))

        now = timezone.localtime(timezone.now())
        backup_settings = BackupSettings.get_solo()
        backup_settings.latest_backup = now - timezone.timedelta(days=1)
        backup_settings.backup_time = (now + timezone.timedelta(seconds=15)).time()
        backup_settings.save()

        # Should not do anything, we should backup a minute from now.
        self.assertFalse(create_backup_mock.called)
        dsmr_backup.services.backup.check()
        self.assertFalse(create_backup_mock.called)

        # Should be fine to backup now. Passed prefered time of user.
        backup_settings.backup_time = now.time()
        backup_settings.save()

        dsmr_backup.services.backup.check()
        self.assertTrue(create_backup_mock.called)
项目:dsmr-reader    作者:dennissiemensma    | 项目源码 | 文件源码
def check():
    """ Checks whether a new backup should be created. Creates one if needed as well. """
    backup_settings = BackupSettings.get_solo()

    # Skip when backups disabled.
    if not backup_settings.daily_backup:
        return

    # Postpone when we already created a backup today.
    if backup_settings.latest_backup and backup_settings.latest_backup.date() == timezone.now().date():
        return

    # Timezone magic to make sure we select and combine the CURRENT day, in the user's timezone.
    next_backup_timestamp = timezone.make_aware(timezone.datetime.combine(
        timezone.localtime(timezone.now()), backup_settings.backup_time
    ))

    if backup_settings.latest_backup and timezone.now() < next_backup_timestamp:
        # Postpone when the user's backup time preference has not been passed yet.
        return

    # For backend logging in Supervisor.
    print(' - Creating new backup.')
    create()
项目:dsmr-reader    作者:dennissiemensma    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        context_data = super(Statistics, self).get_context_data(**kwargs)
        context_data['capabilities'] = dsmr_backend.services.get_capabilities()

        try:
            context_data['latest_reading'] = DsmrReading.objects.all().order_by('-pk')[0]
        except IndexError:
            pass

        today = timezone.localtime(timezone.now()).date()
        context_data['datalogger_settings'] = DataloggerSettings.get_solo()
        context_data['meter_statistics'] = MeterStatistics.get_solo()

        try:
            context_data['energy_prices'] = EnergySupplierPrice.objects.by_date(today)
        except EnergySupplierPrice.DoesNotExist:
            pass

        return context_data
项目:Bitpoll    作者:fsinfuhh    | 项目源码 | 文件源码
def __init__(self, datetime, part, tz):
        self.datetime = localtime(datetime, tz)
        self.part = part
项目:parkkihubi    作者:City-of-Helsinki    | 项目源码 | 文件源码
def __str__(self):
        start = localtime(self.time_start).replace(tzinfo=None)

        if self.time_end is None:
            return "%s -> (%s)" % (start, self.registration_number)

        if self.time_start.date() == self.time_end.date():
            end = localtime(self.time_end).time().replace(tzinfo=None)
        else:
            end = localtime(self.time_end).replace(tzinfo=None)

        return "%s -> %s (%s)" % (start, end, self.registration_number)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def _sqlite_datetime_parse(dt, tzname):
    if dt is None:
        return None
    try:
        dt = backend_utils.typecast_timestamp(dt)
    except (ValueError, TypeError):
        return None
    if tzname is not None:
        dt = timezone.localtime(dt, pytz.timezone(tzname))
    return dt
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def timezone_today():
    """
    Return the current date in the current time zone.
    """
    if settings.USE_TZ:
        return timezone.localtime(timezone.now()).date()
    else:
        return datetime.date.today()
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def localtime(value):
    """
    Converts a datetime to local time in the active time zone.

    This only makes sense within a {% localtime off %} block.
    """
    return do_timezone(value, timezone.get_current_timezone())
项目:mccelections    作者:mcclatchy    | 项目源码 | 文件源码
def limit_candidate_choices():
        today = timezone.localtime(timezone.now()).date()
        time_offset = today - timedelta(days=60)
        return {"dataentry": "manual", "electiondate__gte": time_offset}
项目:mccelections    作者:mcclatchy    | 项目源码 | 文件源码
def limit_election_choices():
        today = timezone.localtime(timezone.now()).date()
        time_offset = today - timedelta(days=60)
        return {"electiondate__gte": time_offset}
项目:mccelections    作者:mcclatchy    | 项目源码 | 文件源码
def limit_race_choices():
        today = timezone.localtime(timezone.now()).date()
        time_offset = today - timedelta(days=60)
        return {"dataentry": "manual", "electiondate__gte": time_offset}

    ## election_fk was removed bc it now pulls that info from the race_fk, but then added back and not exposed bc of a resultmanual error on test server
项目:mccelections    作者:mcclatchy    | 项目源码 | 文件源码
def limit_race_choices():
        today = timezone.localtime(timezone.now()).date()
        time_offset = today - timedelta(days=60)
        return {"dataentry": "manual", "electiondate__gte": time_offset}
项目:mccelections    作者:mcclatchy    | 项目源码 | 文件源码
def limit_candidate_choices():
        today = timezone.localtime(timezone.now()).date()
        time_offset = today - timedelta(days=60)
        return {"dataentry": "manual", "electiondate__gte": time_offset}
项目:mccelections    作者:mcclatchy    | 项目源码 | 文件源码
def limit_reportingunit_choices():
        today = timezone.localtime(timezone.now()).date()
        time_offset = today - timedelta(days=60)
        return {"electiondate__gte": time_offset}