当前位置: 首页>>代码示例>>Python>>正文


Python dateformat.DateFormat类代码示例

本文整理汇总了Python中django.utils.dateformat.DateFormat的典型用法代码示例。如果您正苦于以下问题:Python DateFormat类的具体用法?Python DateFormat怎么用?Python DateFormat使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了DateFormat类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: places

def places(request):
	context_dict = {}
	if request.method == 'POST':
		from_station = request.POST.get('from_station')
		to_station = request.POST.get('to_station')
		date = request.POST.get('departure_date')
		time = request.POST.get('departure_time')
		train_number = request.POST.get('train_number')
		departure_date = datetime.strptime(date, "%Y-%m-%d")
		client = Client(api_usernumber = conf.USER_NUMBER, api_passmd5 = conf.USER_PASSMD5, id_terminal = conf.ID_TERMINAL, id_service = conf.ID_SERVICE, request_url = conf.API_URL)
		df = DateFormat(departure_date)
		places = client.get_train_places(from_station, to_station, df.format('d.m.Y'), time, train_number)
		data = json.dumps(places, ensure_ascii=False)
		response_dict = json.loads(data)
		if 'status' in response_dict:
			context_dict['error'] = response_dict['message']
		else:
			context_dict = place_handler(response_dict)
		context_dict['data'] = data
		context_dict['from_station'] = Station.objects.get(code=from_station)
		context_dict['to_station'] = Station.objects.get(code=to_station)
		context_dict['departure_date'] = date
		context_dict['departure_time'] = time
		context_dict['train_number'] = train_number
		context_dict['stations'] = Station.objects.all()
	return render(request, 'search/places.html', context_dict)
开发者ID:lionlinekz,项目名称:ticketfinder,代码行数:26,代码来源:views.py

示例2: date_as_block_filter

def date_as_block_filter(value):
    df = DateFormat(value)
    result = '''<{0} class="day">{1}</{0}>
        <{0} class="month">{2}</{0}>
        <{0} class="year">{3}</{0}>'''.format(
        'span', df.format('d'), df.format('M'), df.format('Y'))
    return mark_safe(result)
开发者ID:kingsdigitallab,项目名称:gssn-django,代码行数:7,代码来源:cms_tags.py

示例3: _format_json_list

    def _format_json_list(self, obj, options):
        if (len(obj) > 0):
            result = []

            for occ in obj:
                df = DateFormat(occ.created_at)
                new_date = df.format('m/d/Y H:i:s')

                o = {	'is_owner': is_owner(occ.id, options['request_user_id']),
                      'id': occ.id,
                      'user_id': occ.user_id,
                      'created_at': str(new_date),
                      'coordinate': occ.coordinate,
                      'category_id': occ.category_id,
                      'category_name': occ.category.name,
                      'title': occ.title,
                      'description': occ.description,
                      'validated': occ.validated,
                      'vote_counter': occ.vote_counter
                      }
                result.append(o)

            return simplejson.dumps(result)
        else:
            return simplejson.dumps({'Success': False})
开发者ID:mlimaloureiro,项目名称:ihsb1546-12354,代码行数:25,代码来源:formatter.py

示例4: get_occurrence

def get_occurrence(request, ident, user):
    result = {}
    result["success"] = False
    path = settings.CDN_URL + "/static/"

    occ = Occurrences.objects.get(id=int(ident))

    df = DateFormat(occ.created_at)
    new_date = df.format('m/d/Y H:i:s')
    result["occurrence"] = {'id_occ': occ.id, 
                            'user_id': occ.user_id, 
                            'created_at': str(new_date), 
                            'coordinate': occ.coordinate, 
                            'category_id': occ.category_id, 
                            'category_name': occ.category.name, 
                            'title': occ.title, 
                            'description': occ.description, 
                            'vote_counter': occ.vote_counter}
    occ_photos = occ.photos_set.all()
    result["occurrence"]["photos"] = []
    userObj = User.objects.get(id=int(user))
    result["occurrence"]["is_following"] = is_following(occ, userObj)

    for photo in occ_photos:
        result["occurrence"]["photos"].append(
            {"path_small": path + photo.path_small,
             "path_big": path + photo.path_big,
             "path_medium": path + photo.path_medium})

    result["success"] = True
    return HttpResponse(simplejson.dumps(result), content_type="json")
开发者ID:mlimaloureiro,项目名称:ihsb1546-12354,代码行数:31,代码来源:mobile.py

示例5: recently_read

def recently_read(**kwargs):
    """ return html containing data from the recently read list
        Specify an argument n=[int] to determine how many entries
        are rendered in the list.
    """
    num_entries = int(kwargs['n']) if 'n' in kwargs else lib.NUM_READ_LIST
    read_list = ReadingListItem.objects.filter(wishlist=False).order_by('-date_published')[:num_entries]

    list_html = format_html("<h3>Recently Read</h3><div class=\"book-list\">")
    for book in read_list:
        list_html += format_html("<div class='book-book-result book-book-result-hover group'>")
        list_html += format_html("<img src='{}' class='left'>", book.cover)
        list_html += format_html("<p class='title'>{}</p>", book.title)
        list_html += format_html("<p class='author'>{}</p>", book.author)
        list_html += format_html("<p class='description'>{}</p>", book.description)

        dt = DateFormat(book.date_published)
        list_html += format_html("<p class='date'>Added on {}</p>", dt.format("F j, Y g:i A"))

        if book.favorite:
            list_html += format_html("<span class='favorite' title='Cory\'s Favorites'>&#x2605;</span>")

        list_html += format_html("<a class='overlay' href='{}' target='_blank'></a></div>", book.link)

    if len(read_list) == 0:
        list_html += format_html("<p class='empty'>Cory hasn't read any books yet!</p>")

    list_html += format_html("<p class='empty'><a href='{}'>(See More)</a></p></div>", reverse('books'))
    return list_html
开发者ID:CoryParsnipson,项目名称:slackerparadise,代码行数:29,代码来源:blog_extras.py

示例6: test_list_measurement

def test_list_measurement(admin_client, live_server,  # pylint: disable=R0914
                          webdriver):
    selenium = webdriver()
    create_correct_sample_data()
    create_characteristic_values()
    try:
        selenium.get(live_server + '/measurement/')
        login_as_admin(selenium)
        title = selenium.find_element_by_css_selector('#page-wrapper h1').text
        assert title == 'List of measurements'
        table_rows = selenium.find_elements_by_class_name('clickable-row')
        assert len(table_rows) == 19
        all_meas = Measurement.objects.all()
        header = selenium.find_elements_by_css_selector('#page-wrapper th')
        assert len(header) == 6
        for index, field_name in enumerate(['date', 'order', 'order_items',
                                            'examiner', 'meas_item',
                                            'measurement_tag']):
            field = Measurement._meta.get_field(field_name)  # pylint: disable=W0212
            assert header[index].text == field.verbose_name
        for index, row in enumerate(table_rows):
            url = '/measurement/{}/'.format(all_meas[index].pk)
            assert row.get_attribute('data-href') == url
            columns = row.find_elements_by_css_selector('#page-wrapper td')
            assert len(columns) == 6
            date = DateFormat(all_meas[index].date)
            assert columns[0].text == date.format(settings.DATETIME_FORMAT)
            assert columns[1].text == str(all_meas[index].order).strip()
            items = all_meas[index].order_items.all()
            assert columns[2].text == ';'.join([str(item) for item in items])
            assert columns[3].text == all_meas[index].examiner.username
            assert columns[4].text == str(all_meas[index].meas_item)
            assert columns[5].text == str(all_meas[index].measurement_tag)
    finally:
        selenium.quit()
开发者ID:RedBeardCode,项目名称:DjConChart,代码行数:35,代码来源:test_measurement.py

示例7: get_value

 def get_value(self, value):
     if isinstance(value, date):
         date_format = DateFormat(value)
         return date_format.format("d/m/y").capitalize()
     elif isinstance(value, datetime):
         date_format = DateFormat(value)
         return date_format.format("d/m/y H:M").capitalize()
     return value
开发者ID:Maxence42,项目名称:balafon,代码行数:8,代码来源:generic.py

示例8: get_initial

    def get_initial(self):
        self.year = int(self.kwargs["year"])
        self.month = int(self.kwargs["month"])
        self.day = int(self.kwargs["day"])
        dt = date(self.year, self.month, self.day)
        df = DateFormat(dt)
        
	return {'date': date(self.year, self.month, self.day), 'title': ("%s -" % df.format('F jS')), 'user':self.request.user.username}
开发者ID:MacAnthony,项目名称:postschedule,代码行数:8,代码来源:views.py

示例9: occurrences

def occurrences(request):

    user = User.objects.get(id=request.user.id)

    occurrences_objects = Occurrences.objects.filter(
        user=user, bullshit=0).order_by('created_at')
    forcing_objects = OccurrencesReforce.objects.filter(user=user)

    result = []

    # query for own occurrences
    if (len(occurrences_objects) > 0):
        for occ in occurrences_objects:
            df = DateFormat(occ.created_at)
            new_date = df.format('m/d/Y H:i:s')

            o = {'is_owner': 1, 
                 'id': occ.id, 
                 'user_id': occ.user_id, 
                 'user_name': user.username, 
                 'created_at': str(new_date), 
                 'coordinate': occ.coordinate, 
                 'category_id': occ.category_id, 
                 'forced': 0, 
                 'category_name': occ.category.name, 
                 'title': occ.title, 
                 'description': occ.description, 
                 'validated': occ.validated, 
                 'vote_counter': occ.vote_counter}
            result.append(o)

    # query for occurrences user follows
    if(forcing_objects.exists()):
        for forcing in forcing_objects:
            occ = forcing.occurrence

            df = DateFormat(occ.created_at)
            new_date = df.format('m/d/Y H:i:s')

            perm = has_write_permission(occ.id, request.user.id)

            o = {'permission': perm,
                 'is_owner': 0, 
                 'id': occ.id, 
                 'user_id': occ.user_id, 
                 'user_name': occ.user.username, 
                 'created_at': str(new_date), 
                 'coordinate': occ.coordinate, 
                 'category_id': occ.category_id, 
                 'forced': 1, 
                 'category_name': occ.category.name, 
                 'title': occ.title, 
                 'description': occ.description, 
                 'validated': occ.validated, 
                 'vote_counter': occ.vote_counter}
            result.append(o)

    return HttpResponse(simplejson.dumps(result), content_type="json")
开发者ID:mlimaloureiro,项目名称:ihsb1546-12354,代码行数:58,代码来源:users.py

示例10: server_time

def server_time(request):
    """ AJAX call to get the current server time. """
    
    if request.is_ajax():
        df = DateFormat(datetime.now())
        payload = df.format("F jS Y @ h:iA")
    else:
        payload = "Sorry, this URL is for AJAX calls only."
    return HttpResponse(payload, mimetype="text/plain")
开发者ID:froyobin,项目名称:keyholeclass,代码行数:9,代码来源:ajax.py

示例11: serialize_for_ajax

 def serialize_for_ajax(self):
     """ Serializes the time, puzzle, team, and status fields for ajax transmission """
     message = dict()
     df = DateFormat(self.submission_time.astimezone(time_zone))
     message['time_str'] = df.format("h:i a")
     message['puzzle'] = self.puzzle.serialize_for_ajax()
     message['team_pk'] = self.team.pk
     message['status_type'] = "submission"
     return message
开发者ID:dlareau,项目名称:puzzlehunt_server,代码行数:9,代码来源:models.py

示例12: rfc3339

def rfc3339(value):
    from django.utils.dateformat import DateFormat
    if not value:
        return u''
    try:
        df = DateFormat(value)
        offset = (lambda seconds: u"%+03d:%02d" % (seconds // 3600, (seconds // 60) % 60))(df.Z())
        return df.format("Y-m-d\TH:i:s") + offset
    except AttributeError:
        return ''
开发者ID:Gert-Jan,项目名称:DoubleDutchGamesBlog,代码行数:10,代码来源:bloggart_tags.py

示例13: sales_items_paginate

def sales_items_paginate(request):
	page = int(request.GET.get('page'))
	list_sz = request.GET.get('size')
	p2_sz = request.GET.get('psize')
	select_sz = request.GET.get('select_size')
	date = request.GET.get('gid')
	sales = Sales.objects.all().order_by('-id')
	today_formart = DateFormat(datetime.date.today())
	today = today_formart.format('Y-m-d')
	ts = Sales.objects.filter(created__icontains=today)
	tsum = ts.aggregate(Sum('total_net'))
	total_sales = Sales.objects.aggregate(Sum('total_net'))
	total_tax = Sales.objects.aggregate(Sum('total_tax'))

	try:
		last_sale = Sales.objects.latest('id')
		last_date_of_sales = DateFormat(last_sale.created).format('Y-m-d')
		all_sales = Sales.objects.filter(created__contains=last_date_of_sales)
		total_sales_amount = all_sales.aggregate(Sum('total_net'))
		items = SoldItem.objects.values('product_name', 'product_category', 'sku', 'quantity',
										   'unit_cost') \
			.annotate(Count('sku')) \
			.annotate(Sum('total_cost')) \
			.annotate(Sum('unit_cost')) \
			.annotate(Sum('quantity')).order_by('product_name')
		total_items = []
		for t in items:
			product = ProductVariant.objects.get(sku=t['sku'])
			try:
				itemPrice = product.get_cost_price().gross * t['quantity']
				retailPrice = product.get_cost_price().gross
			except ValueError, e:
				itemPrice = product.get_cost_price() * t['quantity']
				retailPrice = product.get_cost_price()
			except:
				itemPrice = 0
				retailPrice = 0
			unitSalesCost = t['unit_cost']
			totalSalesCost = t['total_cost__sum']
			try:
				grossProfit = unitSalesCost - itemPrice
				unitMargin = unitSalesCost - retailPrice
				salesMargin = totalSalesCost - (itemPrice)
				totalCost = retailPrice * t['quantity']
			except:
				grossProfit = 0
				unitMargin = 0
				salesMargin = 0
				totalCost = 0
			t['unitMargin'] = unitMargin
			t['salesMargin'] = salesMargin
			t['retailPrice'] = retailPrice
			t['totalCost'] = totalCost
			total_items.append(t)
开发者ID:glosoftgroup,项目名称:Hardware,代码行数:54,代码来源:sales_margin2.py

示例14: send_chat_message

def send_chat_message(message):
    redis_publisher = RedisPublisher(facility='chat_message',
                      users=[settings.ADMIN_ACCT, message.team.login_info.username])
    packet = dict()
    packet['team_pk'] = message.team.pk
    packet['team_name'] = message.team.team_name
    packet['text'] = message.text
    packet['is_response'] = message.is_response
    df = DateFormat(message.time.astimezone(time_zone))
    packet['time'] = df.format("h:i a")
    packet = RedisMessage(json.dumps(packet))
    redis_publisher.publish_message(packet)
开发者ID:timparenti,项目名称:puzzlehunt_server,代码行数:12,代码来源:redis.py

示例15: entries_by_date

 def entries_by_date(self, request, year, month=None, day=None, *args, **kwargs):
     self.entries = self.get_entries().filter(date__year=year)
     self.search_type = _('date')
     self.search_term = year
     if month:
         self.entries = self.entries.filter(date__month=month)
         df = DateFormat(date(int(year), int(month), 1))
         self.search_term = df.format('F Y')
     if day:
         self.entries = self.entries.filter(date__day=day)
         self.search_term = date_format(date(int(year), int(month), int(day)))
     return Page.serve(self, request, *args, **kwargs)
开发者ID:carltongibson,项目名称:puput,代码行数:12,代码来源:routes.py


注:本文中的django.utils.dateformat.DateFormat类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。