def get_dashboard_blocks(self, request): if not self.check_demo_optin(request): return locale = get_current_babel_locale() n = now() weekday = format_date(n, "EEEE", locale=locale) today = format_date(n, locale=locale) yield DashboardValueBlock( id="test-x", color="blue", title="Happy %s!" % weekday, value=today, icon="fa fa-calendar" ) yield DashboardNumberBlock( id="test-x", color="red", title="Visitors Yesterday", value=random.randint(2200, 10000), icon="fa fa-globe" ) yield DashboardNumberBlock(id="test-x", color="gray", title="Registered Users", value=1240, icon="fa fa-user") yield DashboardNumberBlock(id="test-x", color="orange", title="Orders", value=32, icon="fa fa-inbox") yield DashboardMoneyBlock( id="test-x", color="green", title="Open Orders Value", value=32000, currency="USD", icon="fa fa-line-chart" ) yield DashboardNumberBlock(id="test-x", color="yellow", title="Current Visitors", value=6, icon="fa fa-users") yield DashboardMoneyBlock( id="test-x", color="none", title="Sales this week", value=430.30, currency="USD", icon="fa fa-dollar" ) yield DashboardValueBlock( id="test-1", value="\u03C0", title="The most delicious number", color="purple", icon="fa fa-smile-o" )
def test_format_date(): d = date(2007, 4, 1) assert dates.format_date(d, locale='en_US') == u'Apr 1, 2007' assert (dates.format_date(d, format='full', locale='de_DE') == u'Sonntag, 1. April 2007') assert (dates.format_date(d, "EEE, MMM d, ''yy", locale='en') == u"Sun, Apr 1, '07")
def statistics(self): c.locations = meta.Session.query(Region, func.count(User.id)).filter(LocationTag.region_id == Region.id).filter(User.location_id == LocationTag.id).group_by(Region).all() c.geo_locations = meta.Session.query(User.location_city, func.count(User.id)).group_by(User.location_city).order_by(desc(func.count(User.id))).all() # Getting last week date range locale = c.locale from_time_str = format_date(date.today() - timedelta(7), format="short", locale=locale) to_time_str = format_date(date.today() + timedelta(1), format="short", locale=locale) from_time = parse_date(from_time_str, locale=locale) to_time = parse_date(to_time_str, locale=locale) uploads_stmt = meta.Session.query( Event.author_id, func.count(Event.created).label('uploads_count'))\ .filter(Event.event_type == 'file_uploaded')\ .filter(Event.created < to_time)\ .filter(Event.created >= from_time)\ .group_by(Event.author_id).order_by(desc('uploads_count')).limit(10).subquery() c.active_users = meta.Session.query(User, uploads_stmt.c.uploads_count.label('uploads'))\ .join((uploads_stmt, uploads_stmt.c.author_id == User.id)).all() return render('/statistics.mako')
def get_bar_graph_datas(self): data = [] today = datetime.strptime(fields.Date.context_today(self), DF) data.append({'label': _('Past'), 'value': 0.0, 'type': 'past'}) day_of_week = int(format_datetime(today, 'e', locale=self._context.get( 'lang') or 'en_US')) first_day_of_week = today + timedelta(days=-day_of_week + 1) for i in range(-1, 4): if i == 0: label = _('This Week') elif i == 3: label = _('Future') else: start_week = first_day_of_week + timedelta(days=i * 7) end_week = start_week + timedelta(days=6) if start_week.month == end_week.month: label = \ str(start_week.day) + '-' + str(end_week.day) + ' ' + \ format_date(end_week, 'MMM', locale=self._context.get( 'lang') or 'en_US') else: label = \ format_date(start_week, 'd MMM', locale=self._context.get('lang') or 'en_US' ) + '-' + format_date( end_week, 'd MMM', locale=self._context.get('lang') or 'en_US') data.append({ 'label': label, 'value': 0.0, 'type': 'past' if i < 0 else 'future'}) select_sql_clause = 'SELECT count(*) FROM helpdesk_ticket AS h ' \ 'WHERE issue_type_id = %(issue_type_id)s' query_args = {'issue_type_id': self.id} query = '' start_date = (first_day_of_week + timedelta(days=-7)) for i in range(0, 6): if i == 0: query += "(" + select_sql_clause + " and start_date < '" + \ start_date.strftime(DF) + "')" elif i == 5: query += " UNION ALL (" + select_sql_clause + \ " and start_date >= '" + \ start_date.strftime(DF) + "')" else: next_date = start_date + timedelta(days=7) query += " UNION ALL (" + select_sql_clause + \ " and start_date >= '" + start_date.strftime(DF) + \ "' and end_date < '" + next_date.strftime(DF) + \ "')" start_date = next_date self.env.cr.execute(query, query_args) query_results = self.env.cr.dictfetchall() for index in range(0, len(query_results)): if query_results[index]: data[index]['value'] = query_results[index].get('count') return [{'values': data}]
def get_dates(cls, context): start_date, end_date = context.build_dates if not start_date or not end_date: return '' start_date_str = format_date(start_date, 'd MMMM YYYY', locale='ru') end_date_str = format_date(end_date, 'd MMMM YYYY', locale='ru') return u'%s - %s' % (start_date_str, end_date_str)
def date(datetime, lang): """Format a date depending on current locale""" if lang is None: lang = settings.LANGUAGE try: r = format_date(datetime, locale=lang) except UnknownLocaleError: r = format_date(datetime, locale=settings.LANGUAGE) return r
def POST_update_pay(self, form, jquery, link, campaign, customer_id, pay_id, edit, address, creditcard): if not g.authorizenetapi: return if not link or not campaign or link._id != campaign.link_id: return abort(404, 'not found') # Check inventory if campaign_has_oversold_error(form, campaign): return # check that start is not so late that authorization hold will expire max_start = promote.get_max_startdate() if campaign.start_date > max_start: msg = _("please change campaign start date to %(date)s or earlier") date = format_date(max_start, format="short", locale=c.locale) msg %= {'date': date} form.set_html(".status", msg) return # check the campaign start date is still valid (user may have created # the campaign a few days ago) now = promote.promo_datetime_now() min_start = now + timedelta(days=g.min_promote_future) if campaign.start_date.date() < min_start.date(): msg = _("please change campaign start date to %(date)s or later") date = format_date(min_start, format="short", locale=c.locale) msg %= {'date': date} form.set_html(".status", msg) return address_modified = not pay_id or edit if address_modified: address_fields = ["firstName", "lastName", "company", "address", "city", "state", "zip", "country", "phoneNumber"] card_fields = ["cardNumber", "expirationDate", "cardCode"] if (form.has_errors(address_fields, errors.BAD_ADDRESS) or form.has_errors(card_fields, errors.BAD_CARD)): return pay_id = edit_profile(c.user, address, creditcard, pay_id) reason = None if pay_id: success, reason = promote.auth_campaign(link, campaign, c.user, pay_id) if success: form.redirect(promote.promo_edit_url(link)) return msg = reason or _("failed to authenticate card. sorry.") form.set_html(".status", msg)
def test_format_date(self): import datetime from babel.dates import format_date from babel.core import UnknownLocaleError api = self.make() first = datetime.date(2012, 1, 1) self.assertEqual(api.format_date(first), format_date(first, format="medium", locale="en")) self.assertEqual(api.format_date(first, format="short"), format_date(first, format="short", locale="en")) api.locale_name = "unknown" self.assertRaises(UnknownLocaleError, api.format_date, first)
def get_week_name(start_date, locale): """ Generates a week name (string) from a datetime according to the locale: E.g.: locale start_date (datetime) return string "en_US" November 16th "16-22 Nov" "en_US" December 28th "28 Dec-3 Jan" """ if (start_date + relativedelta(days=6)).month == start_date.month: short_name_from = format_date(start_date, 'd', locale=locale) else: short_name_from = format_date(start_date, 'd MMM', locale=locale) short_name_to = format_date(start_date + relativedelta(days=6), 'd MMM', locale=locale) return short_name_from + '-' + short_name_to
def get_bar_graph_datas(self): data = [] today = fields.Datetime.now(self) data.append({'label': _('Past'), 'value':0.0, 'type': 'past'}) day_of_week = int(format_datetime(today, 'e', locale=self._context.get('lang') or 'en_US')) first_day_of_week = today + timedelta(days=-day_of_week+1) for i in range(-1,4): if i==0: label = _('This Week') elif i==3: label = _('Future') else: start_week = first_day_of_week + timedelta(days=i*7) end_week = start_week + timedelta(days=6) if start_week.month == end_week.month: label = str(start_week.day) + '-' +str(end_week.day)+ ' ' + format_date(end_week, 'MMM', locale=self._context.get('lang') or 'en_US') else: label = format_date(start_week, 'd MMM', locale=self._context.get('lang') or 'en_US')+'-'+format_date(end_week, 'd MMM', locale=self._context.get('lang') or 'en_US') data.append({'label':label,'value':0.0, 'type': 'past' if i<0 else 'future'}) # Build SQL query to find amount aggregated by week (select_sql_clause, query_args) = self._get_bar_graph_select_query() query = '' start_date = (first_day_of_week + timedelta(days=-7)) for i in range(0,6): if i == 0: query += "("+select_sql_clause+" and date_due < '"+start_date.strftime(DF)+"')" elif i == 5: query += " UNION ALL ("+select_sql_clause+" and date_due >= '"+start_date.strftime(DF)+"')" else: next_date = start_date + timedelta(days=7) query += " UNION ALL ("+select_sql_clause+" and date_due >= '"+start_date.strftime(DF)+"' and date_due < '"+next_date.strftime(DF)+"')" start_date = next_date self.env.cr.execute(query, query_args) query_results = self.env.cr.dictfetchall() is_sample_data = True for index in range(0, len(query_results)): if query_results[index].get('aggr_date') != None: is_sample_data = False data[index]['value'] = query_results[index].get('total') [graph_title, graph_key] = self._graph_title_and_key() if is_sample_data: for index in range(0, len(query_results)): data[index]['type'] = 'o_sample_data' # we use unrealistic values for the sample data data[index]['value'] = random.randint(0, 20) graph_key = _('Sample data') return [{'values': data, 'title': graph_title, 'key': graph_key, 'is_sample_data': is_sample_data}]
def _render_report(self, report): if not report.rendered: report_data = report.get_data() self.write_heading( "{title} {start} - {end}".format( title=report.title, start=format_date(report_data["start"], format="short", locale=get_current_babel_locale()), end=format_date(report_data["end"], format="short", locale=get_current_babel_locale())) ) report.ensure_texts() self.write_data_table(report, report_data["data"], has_totals=report_data["has_totals"]) return self.get_rendered_output()
def _parse_file(self, data_file): locale = self._context.get("lang", "en_US") ofx = self.validate_ofx(StringIO.StringIO(data_file)) transactions = [] total_amt = 0.00 for transaction in ofx.account.statement.transactions: bank_account_id = partner_id = False partner_bank = self.env["res.partner.bank"].search([("partner_id.name", "=", transaction.payee)], limit=1) if partner_bank: bank_account_id = partner_bank.id partner_id = partner_bank.partner_id.id vals_line = { "date": transaction.date, "name": transaction.payee + (transaction.memo and ": " + transaction.memo or ""), "ref": u"{}: {}".format( int(transaction.id) - 1, format_date(transaction.date, "EEEE d", locale=locale) ), "amount": transaction.amount, "unique_import_id": "{}-{}".format( transaction.id, transaction.date.strftime(DEFAULT_SERVER_DATE_FORMAT) ), "bank_account_id": bank_account_id, "partner_id": partner_id, } total_amt += float(transaction.amount) transactions.append(vals_line) dates = [st.date for st in ofx.account.statement.transactions] min_date = min(dates) max_date = max(dates) vals_bank_statement = { "name": "Del {} al {} de {}".format( min_date.strftime("%d"), max_date.strftime("%d"), format_date(max_date, "MMMM", locale=locale) ), "transactions": transactions, "balance_start": float(ofx.account.statement.balance) - total_amt, "balance_end_real": ofx.account.statement.balance, "date": max_date.strftime(DEFAULT_SERVER_DATE_FORMAT), } bank_journal_id = self.env["account.journal"].search([("bank_acc_number", "=", ofx.account.number)]) if not bank_journal_id: raise UserError(u"Debe espesificar el número de la cuenta del banco en el diario!") bank_import_type = bank_journal_id.bank_id.statement_import_type currency = ofx.account.statement.currency if bank_import_type == "bpdofx": currency = "DOP" return currency, ofx.account.number, [vals_bank_statement]
def date_picker(start_date, end_date, in_format='%Y-%m-%d', out_format='d MMMM yyyy', locale='en_US'): dstart = datetime.strptime(start_date, in_format) if not end_date: return format_date(dstart, out_format, locale=locale) else: dend = datetime.strptime(end_date, in_format) if dstart.year != dend.year: # full dates for different years return '%s-%s' % (format_date(dstart, out_format, locale=locale), format_date(dend, out_format, locale=locale)) else: if dstart.month != dend.month: # same years, different months return '%s-%s' % (format_date(dstart, 'd MMMM', locale=locale), format_date(dend, out_format, locale=locale)) else: if dstart.day != dend.day: # same year, same month, different days return '%s-%s' % (format_date(dstart, 'd', locale=locale), format_date(dend, out_format, locale=locale)) else: # same date return format_date(dstart, out_format, locale=locale)
def date_processor(date_start, date_end, in_format='%Y-%m-%d', out_format='d MMMM yyyy', locale='en_US'): if not date_end: return format_date(date_start, out_format, locale=locale) else: if date_start.year != date_end.year: # full dates for different years return '%s-%s' % ( format_date(date_start, out_format, locale=locale), format_date(date_end, out_format, locale=locale)) else: if date_start.month != date_end.month: # same years, different months return '%s-%s' % ( format_date(date_start, out_format.replace(' yyyy', ''), locale=locale), format_date(date_end, out_format, locale=locale)) else: if date_start.day != date_end.day: # same year, same month, different days return '%s-%s' % ( format_date(date_start, 'd', locale=locale), format_date(date_end, out_format, locale=locale)) else: # same date return format_date(date_start, out_format, locale=locale)
def test_format_date(self, db_session): import datetime from babel.dates import format_date from babel.core import UnknownLocaleError api = self.make() first = datetime.date(2012, 1, 1) assert ( api.format_date(first) == format_date(first, format='medium', locale='en')) assert ( api.format_date(first, fmt='short') == format_date(first, format='short', locale='en')) api.locale_name = 'unknown' with raises(UnknownLocaleError): api.format_date(first)
def test_date(self): """Expects date format.""" value_test = datetime.fromordinal(733900) value_expected = format_date(value_test, locale=u'en_US') value_returned = datetimeformat(self.context, value_test, format='date') eq_(pq(value_returned)('time').text(), value_expected)
def l10n_format_date(date, format='long'): """ Formats a date according to the current locale. Wraps around babel.dates.format_date. """ locale = current_locale() return format_date(date, locale=locale, format=format)
def format_date(self, date=None, format=None, rebase=True): """Returns a date formatted according to the given pattern and following the current locale. :param date: A ``date`` or ``datetime`` object. If None, the current date in UTC is used. :param format: The format to be returned. Valid values are "short", "medium", "long", "full" or a custom date/time pattern. Example outputs: - short: 11/10/09 - medium: Nov 10, 2009 - long: November 10, 2009 - full: Tuesday, November 10, 2009 :param rebase: If True, converts the date to the current :attr:`timezone`. :returns: A formatted date in unicode. """ format = self._get_format('date', format) if rebase and isinstance(date, datetime.datetime): date = self.to_local_timezone(date) return dates.format_date(date, format, locale=self.locale)
def test_smoke_dates(locale): locale = Locale.parse(locale) instant = datetime.now() for width in ("full", "long", "medium", "short"): assert dates.format_date(instant, format=width, locale=locale) assert dates.format_datetime(instant, format=width, locale=locale) assert dates.format_time(instant, format=width, locale=locale)
def l10n_format_date(ctx, date, format='long'): """ Formats a date according to the current locale. Wraps around babel.dates.format_date. """ lang = get_locale(ctx['LANG']) return format_date(date, locale=lang, format=format)
def do_run_scheduler(self, cr, uid, automatic=False, use_new_cursor=False, context=None): res_users_obj = self.pool.get('res.users') users_active_obj = self.pool.get('users.active') res_lang_obj = self.pool.get('res.lang') #Solo tener en cuenta usuarios que esten activos Y que aciven su cuenta. users_ids = res_users_obj.search(cr, uid,[('active','=',True),('login_date','!=',False)]) nb_active_users = len(users_ids) # Lang of user : need format user = res_users_obj.browse(cr, uid, uid) lang_ids = res_lang_obj.search(cr, uid, [('code','=',user.lang)]) if len(lang_ids) == 1 : lang = res_lang_obj.browse(cr, uid, lang_ids[0]) # Current month date_tmp = datetime.datetime.today() month_str = format_date(date_tmp,"MMMM",locale=lang.code) month_str = month_str[0].upper()+month_str[1:] week = date_tmp.isocalendar()[1] month = int(time.strftime("%m")) if nb_active_users : vals = { 'date' : time.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'month_str' : month_str, 'year' : time.strftime("%Y"), 'month' : month, 'nb_users' : nb_active_users, 'week' : week } nb_active_users_id = users_active_obj.create(cr, SUPERUSER_ID, vals, context=None) cr.commit() return True
def format_date_by_locale(date, locale_string): # strftime works only on dates after 1900 if date.year <= 1900: return date.isoformat().split('T')[0] if locale_string == 'all': locale_string = settings['ui']['default_locale'] or 'en_US' # to avoid crashing if locale is not supported by babel try: formatted_date = format_date(date, locale=locale_string) except: formatted_date = format_date(date, "YYYY-MM-dd") return formatted_date
def datetimeformat(context, value, format='shortdatetime'): """ Returns date/time formatted using babel's locale settings. Uses the timezone from settings.py """ if not isinstance(value, datetime.datetime): # Expecting date value raise ValueError tzinfo = timezone(settings.TIME_ZONE) tzvalue = tzinfo.localize(value) locale = _babel_locale(_contextual_locale(context)) # If within a day, 24 * 60 * 60 = 86400s if format == 'shortdatetime': # Check if the date is today if value.toordinal() == datetime.date.today().toordinal(): formatted = _lazy(u'Today at %s') % format_time( tzvalue, format='short', locale=locale) else: formatted = format_datetime(tzvalue, format='short', locale=locale) elif format == 'longdatetime': formatted = format_datetime(tzvalue, format='long', locale=locale) elif format == 'date': formatted = format_date(tzvalue, locale=locale) elif format == 'time': formatted = format_time(tzvalue, locale=locale) elif format == 'datetime': formatted = format_datetime(tzvalue, locale=locale) else: # Unknown format raise DateTimeFormatError return jinja2.Markup('<time datetime="%s">%s</time>' % \ (tzvalue.isoformat(), formatted))
def datetimeformat(context, value, format='shortdatetime'): """ Returns a formatted date/time using Babel's locale settings. Uses the timezone from settings.py, if the user has not been authenticated. """ if not isinstance(value, datetime.datetime): # Expecting date value raise ValueError request = context.get('request') default_tzinfo = convert_tzinfo = timezone(settings.TIME_ZONE) if value.tzinfo is None: value = default_tzinfo.localize(value) new_value = value.astimezone(default_tzinfo) else: new_value = value if 'timezone' not in request.session: if request.user.is_authenticated(): try: convert_tzinfo = request.user.get_profile().timezone or \ default_tzinfo except (Profile.DoesNotExist, AttributeError): pass request.session['timezone'] = convert_tzinfo else: convert_tzinfo = request.session['timezone'] convert_value = new_value.astimezone(convert_tzinfo) locale = _babel_locale(_contextual_locale(context)) # If within a day, 24 * 60 * 60 = 86400s if format == 'shortdatetime': # Check if the date is today today = datetime.datetime.now(tz=convert_tzinfo).toordinal() if convert_value.toordinal() == today: formatted = _lazy(u'Today at %s') % format_time( convert_value, format='short', tzinfo=convert_tzinfo, locale=locale) else: formatted = format_datetime(convert_value, format='short', tzinfo=convert_tzinfo, locale=locale) elif format == 'longdatetime': formatted = format_datetime(convert_value, format='long', tzinfo=convert_tzinfo, locale=locale) elif format == 'date': formatted = format_date(convert_value, locale=locale) elif format == 'time': formatted = format_time(convert_value, tzinfo=convert_tzinfo, locale=locale) elif format == 'datetime': formatted = format_datetime(convert_value, tzinfo=convert_tzinfo, locale=locale) else: # Unknown format raise DateTimeFormatError return jinja2.Markup('<time datetime="%s">%s</time>' % \ (convert_value.isoformat(), formatted))
def i_format(loc, s, *a, **kw): if a: a = list(a) for c, f in [(a, enumerate), (kw, dict.items)]: for k, o in f(c): o, wrapper = (o.value, o.wrapper) if isinstance(o, Wrap) else (o, None) if isinstance(o, text_type): pass elif isinstance(o, Decimal): c[k] = format_decimal(o, locale=loc) elif isinstance(o, int): c[k] = format_number(o, locale=loc) elif isinstance(o, Money): c[k] = loc.format_money(o) elif isinstance(o, MoneyBasket): c[k] = loc.format_money_basket(o) elif isinstance(o, Age): c[k] = format_timedelta(o, locale=loc, **o.format_args) elif isinstance(o, timedelta): c[k] = format_timedelta(o, locale=loc) elif isinstance(o, datetime): c[k] = format_datetime(o, locale=loc) elif isinstance(o, date): c[k] = format_date(o, locale=loc) elif isinstance(o, Locale): c[k] = loc.languages.get(o.language) or o.language.upper() elif isinstance(o, Currency): c[k] = loc.currencies.get(o, o) if wrapper: c[k] = wrapper % (c[k],) return s.format(*a, **kw)
def babel_date(date, format='long'): """ Format a date properly for the current locale. Format can be one of 'short', 'medium', 'long', or 'full'. """ locale = current_locale() return format_date(date, format, locale)
def dates_line(self, date, changed): """ Adds the given date and timespamp. """ self.table( [[ format_date(date, format='long', locale=self.locale), '{}: {} {}'.format( self.translate(_('Last change')), format_date(changed, format='long', locale=self.locale), format_time(changed, format='short', locale=self.locale) ) ]], 'even', style=self.style.table_dates )
def asString(self, objValue, objType): ''' @see: Converter.asString ''' assert isinstance(objType, Type), 'Invalid object type %s' % objType if isinstance(objType, TypeModel): # If type model is provided we consider the model property type assert isinstance(objType, TypeModel) container = objType.container assert isinstance(container, Model) objType = container.properties[container.propertyId] if objType.isOf(str): return objValue if objType.isOf(bool): return str(objValue) if objType.isOf(Percentage): return bn.format_percent(objValue, self.formats.get(Percentage, None), self.locale) if objType.isOf(Number): return bn.format_decimal(objValue, self.formats.get(Number, None), self.locale) if objType.isOf(Date): return bd.format_date(objValue, self.formats.get(Date, None), self.locale) if objType.isOf(Time): return bd.format_time(objValue, self.formats.get(Time, None), self.locale) if objType.isOf(DateTime): return bd.format_datetime(objValue, self.formats.get(DateTime, None), None, self.locale) raise TypeError('Invalid object type %s for Babel converter' % objType)
def get_data(self): orders = self.get_objects().order_by("-order_date") data = [] for order_date, orders_group in itertools.groupby(orders, key=self.extract_date): taxless_total = TaxlessPrice(0, currency=self.shop.currency) taxful_total = TaxfulPrice(0, currency=self.shop.currency) paid_total = TaxfulPrice(0, currency=self.shop.currency) product_count = 0 order_count = 0 for order in orders_group: taxless_total += order.taxless_total_price taxful_total += order.taxful_total_price product_count += sum(order.get_product_ids_and_quantities().values()) order_count += 1 if order.payment_date: paid_total += order.taxful_total_price data.append({ "date": format_date(order_date, format="short", locale=get_current_babel_locale()), "order_count": order_count, "product_count": int(product_count), "taxless_total": taxless_total, "taxful_total": taxful_total, }) return self.get_return_data(data)
def when_text(d,t=None): """ Return a string with a concise representation of the given date and time combination. Examples: >>> when_text(datetime.date(2013,12,25)) u'2013 Dec 25 (Wed)' >>> when_text(datetime.date(2013,12,25),datetime.time(17,15,00)) u'2013 Dec 25 (Wed) 17:15' >>> when_text(None) u'' """ if d is None: return '' fmt = 'yyyy MMM dd (EE)' if t is None: return format_date(d,fmt,locale=to_locale(translation.get_language())) #~ if d.year == datetime.date.today().year: #~ fmt = "%a" + settings.SITE.time_format_strftime #~ else: #~ fmt = "%a %y %b %d" + settings.SITE.time_format_strftime #~ fmt = "%a %Y %b %d " + settings.SITE.time_format_strftime #~ return datetime.datetime.combine(d,t).strftime(fmt) fmt += " HH:mm" return format_datetime(datetime.datetime.combine(d,t),fmt,locale=to_locale(translation.get_language()))
def datetimeformat(context, value, format='shortdatetime'): """ Returns a formatted date/time using Babel's locale settings. Uses the timezone from settings.py, if the user has not been authenticated. """ if not isinstance(value, datetime.datetime): # Expecting date value raise ValueError request = context.get('request') default_tzinfo = convert_tzinfo = timezone(settings.TIME_ZONE) if value.tzinfo is None: value = default_tzinfo.localize(value) new_value = value.astimezone(default_tzinfo) else: new_value = value if 'timezone' not in request.session: if request.user.is_authenticated(): try: convert_tzinfo = (request.user.get_profile().timezone or default_tzinfo) except (Profile.DoesNotExist, AttributeError): pass request.session['timezone'] = convert_tzinfo else: convert_tzinfo = request.session['timezone'] convert_value = new_value.astimezone(convert_tzinfo) locale = _babel_locale(_contextual_locale(context)) # If within a day, 24 * 60 * 60 = 86400s if format == 'shortdatetime': # Check if the date is today today = datetime.datetime.now(tz=convert_tzinfo).toordinal() if convert_value.toordinal() == today: formatted = _lazy(u'Today at %s') % format_time( convert_value, format='short', tzinfo=convert_tzinfo, locale=locale) else: formatted = format_datetime(convert_value, format='short', tzinfo=convert_tzinfo, locale=locale) elif format == 'longdatetime': formatted = format_datetime(convert_value, format='long', tzinfo=convert_tzinfo, locale=locale) elif format == 'date': formatted = format_date(convert_value, locale=locale) elif format == 'time': formatted = format_time(convert_value, tzinfo=convert_tzinfo, locale=locale) elif format == 'datetime': formatted = format_datetime(convert_value, tzinfo=convert_tzinfo, locale=locale) else: # Unknown format raise DateTimeFormatError return jinja2.Markup('<time datetime="%s">%s</time>' % (convert_value.isoformat(), formatted))
def get_weekday(self, ui_lang, date): date = self.tz.fromutc(self.tz.localize(date)) return format_date(date, "EEEE", locale=Locale.parse(ui_lang)).capitalize()
def get_bar_graph_datas(self): data = [] title = _('Invoices owed to you') if self.type == 'purchase': title = _('Bills you need to pay') today = datetime.strptime(fields.Date.context_today(self), DF) data.append({'label': _('Past'), 'value': 0.0, 'type': 'past'}) day_of_week = int( format_datetime(today, 'e', locale=self._context.get('lang', 'en_US'))) first_day_of_week = today + timedelta(days=-day_of_week + 1) for i in range(-1, 4): if i == 0: label = _('This Week') elif i == 3: label = _('Future') else: start_week = first_day_of_week + timedelta(days=i * 7) end_week = start_week + timedelta(days=6) if start_week.month == end_week.month: label = str(start_week.day) + '-' + str( end_week.day) + ' ' + format_date( end_week, 'MMM', locale=self._context.get('lang', 'en_US')) else: label = format_date( start_week, 'd MMM', locale=self._context.get( 'lang', 'en_US')) + '-' + format_date( end_week, 'd MMM', locale=self._context.get('lang', 'en_US')) data.append({ 'label': label, 'value': 0.0, 'type': 'past' if i < 0 else 'future' }) # Build SQL query to find amount aggregated by week select_sql_clause = """SELECT sum(residual_signed) as total, min(date) as aggr_date from account_invoice where journal_id = %(journal_id)s and state = 'open'""" query = '' start_date = (first_day_of_week + timedelta(days=-7)) for i in range(0, 6): if i == 0: query += "(" + select_sql_clause + " and date < '" + start_date.strftime( DF) + "')" elif i == 6: query += " UNION ALL (" + select_sql_clause + " and date >= '" + start_date.strftime( DF) + "')" else: next_date = start_date + timedelta(days=7) query += " UNION ALL (" + select_sql_clause + " and date >= '" + start_date.strftime( DF) + "' and date < '" + next_date.strftime(DF) + "')" start_date = next_date self.env.cr.execute(query, {'journal_id': self.id}) query_results = self.env.cr.dictfetchall() for index in range(0, len(query_results)): if query_results[index].get('aggr_date') != None: data[index]['value'] = query_results[index].get('total') return [{'values': data, 'title': title}]
def test_russian_week_numbering(): # See https://github.com/python-babel/babel/issues/485 v = date(2017, 1, 1) assert dates.format_date(v, format='YYYY-ww',locale='ru_RU') == '2016-52' # This would have returned 2017-01 prior to CLDR 32 assert dates.format_date(v, format='YYYY-ww',locale='de_DE') == '2016-52'
def test_sales_report_timezone(server_timezone): with override_settings(TIME_ZONE=server_timezone): """ TIME TABLE | identifier | ISO 8859-1 | UTC | America/Los_Angeles | America/Sao_Paulo | | first_date | 2017-10-01T23:50:00+03:00 | 2017-10-01 20:50:00 | 2017-10-01 13:50:00 | 2017-10-01 17:50:00 | | second_date | 2017-10-02T17:13:00+10:00 | 2017-10-02 07:13:00 | 2017-10-02 00:13:00 | 2017-10-02 04:13:00 | | third_date | 2017-10-02T22:04:44-01:00 | 2017-10-02 23:04:44 | 2017-10-02 16:04:44 | 2017-10-02 20:04:44 | | forth_date | 2017-10-02T23:04:44-05:00 | 2017-10-03 04:04:44 | 2017-10-02 21:04:44 | 2017-10-03 01:04:44 | """ first_date = parse_datetime("2017-10-01T23:50:00+03:00") second_date = parse_datetime("2017-10-02T17:13:00+10:00") third_date = parse_datetime("2017-10-02T22:04:44-01:00") forth_date = parse_datetime("2017-10-02T23:04:44-05:00") inited_data = create_orders_for_dates( [first_date, second_date, third_date, forth_date], as_paid=True) assert Order.objects.count() == 4 first_date_local = first_date.astimezone(timezone(server_timezone)) second_date_local = second_date.astimezone(timezone(server_timezone)) third_date_local = third_date.astimezone(timezone(server_timezone)) forth_date_local = forth_date.astimezone(timezone(server_timezone)) data = { "report": SalesReport.get_name(), "shop": inited_data["shop"].pk, "start_date": first_date_local.isoformat(), "end_date": second_date_local.isoformat(), } report = SalesReport(**data) report_data = report.get_data()["data"] assert len(report_data) == 2 # the orders should be rendered as localtime assert report_data[0]["date"] == format_date( second_date_local, locale=get_current_babel_locale()) assert report_data[1]["date"] == format_date( first_date_local, locale=get_current_babel_locale()) # includes the 3rd order data.update({ "start_date": first_date_local.isoformat(), "end_date": third_date_local.isoformat() }) report = SalesReport(**data) report_data = report.get_data()["data"] assert len(report_data) == 2 assert report_data[0]["date"] == format_date( second_date_local, locale=get_current_babel_locale()) assert report_data[1]["date"] == format_date( first_date_local, locale=get_current_babel_locale()) # includes the 4th order - here the result is different for Los_Angeles and Sao_Paulo data.update({ "start_date": first_date_local.isoformat(), "end_date": forth_date_local.isoformat() }) report = SalesReport(**data) report_data = report.get_data()["data"] if server_timezone == "America/Los_Angeles": assert len(report_data) == 2 assert report_data[0]["date"] == format_date( second_date_local, locale=get_current_babel_locale()) assert report_data[1]["date"] == format_date( first_date_local, locale=get_current_babel_locale()) else: assert len(report_data) == 3 assert report_data[0]["date"] == format_date( forth_date_local, locale=get_current_babel_locale()) assert report_data[1]["date"] == format_date( second_date_local, locale=get_current_babel_locale()) assert report_data[2]["date"] == format_date( first_date_local, locale=get_current_babel_locale())
def test_lithuanian_long_format(): assert ( dates.format_date(date(2015, 12, 10), locale='lt_LT', format='long') == u'2015 m. gruodžio 10 d.' )
def test_with_day_of_year_in_pattern_and_datetime_param(self): # format_date should work on datetimes just as well (see #282) d = datetime(2007, 4, 1) self.assertEqual('14', dates.format_date(d, 'w', locale='en_US'))
def format_date(self, date, format='medium'): if format.endswith('_yearless'): format = self.date_formats[format] return format_date(date, format, locale=self)
def get_bar_graph_datas(self, invoice_type): self.ensure_one() # itemType = self.item_name # if itemType in ['order', 'partner']: # fecthDate = 'create_date' # else: # fecthDate = 'write_date' moduleTable = 'account_invoice' fecthDate = 'date_invoice' data = [] today = datetime.strptime(fields.Date.context_today(self), DF) data.append({'label': _('Past'), 'value': 0.0, 'type': 'past'}) day_of_week = int( format_datetime(today, 'e', locale=self._context.get('lang', 'en_US'))) first_day_of_week = today + timedelta(days=-day_of_week + 1) for i in range(-1, 2): if i == 0: label = _('This Week') elif i == 1: label = _('Future') else: start_week = first_day_of_week + timedelta(days=i * 7) end_week = start_week + timedelta(days=6) if start_week.month == end_week.month: label = str(start_week.day) + '-' + str( end_week.day) + ' ' + format_date( end_week, 'MMM', locale=self._context.get('lang', 'en_US')) else: label = format_date( start_week, 'd MMM', locale=self._context.get( 'lang', 'en_US')) + '-' + format_date( end_week, 'd MMM', locale=self._context.get('lang', 'en_US')) data.append({ 'label': label, 'value': 0.0, 'type': 'past' if i < 0 else 'future' }) # Build SQL query to find amount aggregated by week select_sql_clause = """SELECT COUNT(*) as total FROM """ + moduleTable + """ where invoice_type = %(invoice_type)s """ query = '' start_date = (first_day_of_week + timedelta(days=-7)) for i in range(0, 4): if i == 0: query += "(" + select_sql_clause + " and " + fecthDate + " < '" + start_date.strftime( DF) + "')" elif i == 3: query += " UNION ALL (" + select_sql_clause + " and date >= '" + start_date.strftime( DF) + "')" else: next_date = start_date + timedelta(days=7) query += " UNION ALL (" + select_sql_clause + " and " + fecthDate + " >= '" + start_date.strftime( DF) + "' and " + fecthDate + " < '" + next_date.strftime( DF) + "')" start_date = next_date self.env.cr.execute(query, {'invoice_type': self.invoice_type}) query_results = self.env.cr.dictfetchall() for index in range(0, len(query_results)): total = str(query_results[index].get('total')) total = total.split('L') if total[0] > 0: data[index]['value'] = total[0] return [{'values': data}]
def get_line_graph_datas(self): data = [] today = datetime.today() last_month = today + timedelta(days=-30) bank_stmt = [] # Query to optimize loading of data for bank statement graphs # Return a list containing the latest bank statement balance per day for the # last 30 days for current journal query = """SELECT a.date, a.balance_end FROM account_bank_statement AS a, (SELECT c.date, max(c.id) AS stmt_id FROM account_bank_statement AS c WHERE c.journal_id = %s AND c.date > %s AND c.date <= %s GROUP BY date, id ORDER BY date, id) AS b WHERE a.id = b.stmt_id;""" self.env.cr.execute(query, (self.id, last_month, today)) bank_stmt = self.env.cr.dictfetchall() last_bank_stmt = self.env['account.bank.statement'].search( [('journal_id', 'in', self.ids), ('date', '<=', last_month.strftime(DF))], order="date desc, id desc", limit=1) start_balance = last_bank_stmt and last_bank_stmt[0].balance_end or 0 locale = self._context.get('lang') or 'en_US' show_date = last_month #get date in locale format name = format_date(show_date, 'd LLLL Y', locale=locale) short_name = format_date(show_date, 'd MMM', locale=locale) data.append({'x': short_name, 'y': start_balance, 'name': name}) for stmt in bank_stmt: #fill the gap between last data and the new one number_day_to_add = (datetime.strptime(stmt.get('date'), DF) - show_date).days last_balance = data[len(data) - 1]['y'] for day in range(0, number_day_to_add + 1): show_date = show_date + timedelta(days=1) #get date in locale format name = format_date(show_date, 'd LLLL Y', locale=locale) short_name = format_date(show_date, 'd MMM', locale=locale) data.append({'x': short_name, 'y': last_balance, 'name': name}) #add new stmt value data[len(data) - 1]['y'] = stmt.get('balance_end') #continue the graph if the last statement isn't today if show_date != today: number_day_to_add = (today - show_date).days last_balance = data[len(data) - 1]['y'] for day in range(0, number_day_to_add): show_date = show_date + timedelta(days=1) #get date in locale format name = format_date(show_date, 'd LLLL Y', locale=locale) short_name = format_date(show_date, 'd MMM', locale=locale) data.append({'x': short_name, 'y': last_balance, 'name': name}) [graph_title, graph_key] = self._graph_title_and_key() color = '#875A7B' if '+e' in version else '#7c7bad' return [{ 'values': data, 'title': graph_title, 'key': graph_key, 'area': True, 'color': color }]
def get_bar_graph_datas(self): data = [] today = datetime.strptime(fields.Date.context_today(self), DF) data.append({'label': _('Past'), 'value': 0.0, 'type': 'past'}) day_of_week = int( format_datetime(today, 'e', locale=self._context.get('lang') or 'en_US')) first_day_of_week = today + timedelta(days=-day_of_week + 1) for i in range(-1, 4): if i == 0: label = _('This Week') elif i == 3: label = _('Future') else: start_week = first_day_of_week + timedelta(days=i * 7) end_week = start_week + timedelta(days=6) if start_week.month == end_week.month: label = str(start_week.day) + '-' + str( end_week.day) + ' ' + format_date( end_week, 'MMM', locale=self._context.get('lang') or 'en_US') else: label = format_date(start_week, 'd MMM', locale=self._context.get('lang') or 'en_US') + '-' + format_date( end_week, 'd MMM', locale=self._context.get('lang') or 'en_US') data.append({ 'label': label, 'value': 0.0, 'type': 'past' if i < 0 else 'future' }) # Build SQL query to find amount aggregated by week (select_sql_clause, query_args) = self._get_bar_graph_select_query() query = '' start_date = (first_day_of_week + timedelta(days=-7)) for i in range(0, 6): if i == 0: query += "(" + select_sql_clause + " and date < '" + start_date.strftime( DF) + "')" elif i == 5: query += " UNION ALL (" + select_sql_clause + " and date >= '" + start_date.strftime( DF) + "')" else: next_date = start_date + timedelta(days=7) query += " UNION ALL (" + select_sql_clause + " and date >= '" + start_date.strftime( DF) + "' and date < '" + next_date.strftime(DF) + "')" start_date = next_date self.env.cr.execute(query, query_args) query_results = self.env.cr.dictfetchall() for index in range(0, len(query_results)): if query_results[index].get('aggr_date') != None: data[index]['value'] = query_results[index].get('total') [graph_title, graph_key] = self._graph_title_and_key() return [{'values': data, 'title': graph_title, 'key': graph_key}]
def date_formatting(input, locale): # format_datetime(datetime.datetime.now(), tzinfo=tz, format='full', locale=locale) return format_date(input, format='full', locale=locale)
############################# Elementos de la caratula ##################### ############################################################################ import datetime from babel.dates import format_date #tituloTesina = ("Sistema para detección y reconocimiento de irregularidades sobre circuitos viales utilizando el sensor Kinect").decode("utf-8") tituloTesina = ( "SISTEMA PARA DETECCIÓN Y RECONOCIMIENTO DE IRREGULARIDADES SOBRE CIRCUITOS VIALES UTILIZANDO EL SENSOR KINECT" ).decode("utf-8") # Imagen obtenida con graphics autores = "Autores: Huincalef Rodrigo A. , Urrutia Guillermo G." tutores = "Director de tesina: Ingravallo Gabriel" facultad = "Facultad de ingeniería - Sede Trelew".decode("utf-8") fecha = datetime.date.today() fechaActual = format_date(fecha, "d 'de' MMMM 'del' yyyy", locale='es').title() universidad = "UNPSJB - Universidad Nacional de la Patagonia San Juan Bosco" justificacion = """Tesina presentada a la Facultad de Ingeniería de la Universidad Nacional de la Patagonia San Juan Bosco como parte de los requisitos para la obtención del título de Licenciado en Sistemas""".decode( "utf-8") latex_engine = 'lualatex' # CAMPOS USADOS POR \FANCYHDR --> #E: Even page #O: Odd page #L: Left field #C: Center field #R: Right field #H: Header
def send_payment_notification( order: Order, request: HttpRequest, email: str = None, phone_number: str = None, has_services: bool = True, has_payment_urls: bool = True, ): from payments.providers import get_payment_provider from .notifications import NotificationType order_email = email or order.customer_email order_phone = phone_number or order.customer_phone if not is_valid_email(order_email): raise ValidationError(_("Missing customer email")) language = get_notification_language(order) payment_url = None cancel_url = None if has_payment_urls: payment_url = get_payment_provider( request, ui_return_url=settings.VENE_UI_RETURN_URL).get_payment_email_url( order, lang=language) cancel_url = get_payment_provider( request, ui_return_url=settings.VENE_UI_RETURN_URL ).get_cancellation_email_url(order, lang=language) notification_type = get_order_notification_type(order) context = get_context(order, notification_type, has_services, payment_url, cancel_url) send_notification(order_email, notification_type.value, context, language) if order_phone and notification_type not in ( NotificationType.ORDER_CANCELLED, NotificationType.ORDER_REFUNDED, ): if hasattr(order, "product") and order.product: product_name = order.product.name else: product_name = ", ".join([ str(ProductServiceType(order_line.product.service).label) for order_line in order.order_lines.all() ]) sms_context = { "product_name": product_name, "due_date": format_date(order.due_date, locale=language), "payment_url": payment_url, } sms_service = SMSNotificationService() sms_service.send( NotificationType.SMS_INVOICE_NOTICE, sms_context, order_phone, language=language, )
def test_year_and_month(locale_name, expected): locale = babel.Locale.parse(locale_name) formatted = format_date(datetime.date(1980, 3, 1), format=get_year_and_month_format(locale), locale=locale) assert formatted == expected
def build_graph_data(date, amount): #display date in locale format name = format_date(date, 'd LLLL Y', locale=locale) short_name = format_date(date, 'd MMM', locale=locale) return {'x':short_name,'y': amount, 'name':name}
def test_coupons_usage_report(rf): shop = get_default_shop() tax_class = get_default_tax_class() creator = OrderCreator() coupon1 = Coupon.objects.create(code="coupon1", active=True) coupon2 = Coupon.objects.create(code="coupon2", active=True) campaign1 = get_default_campaign(coupon1, "10") campaign2 = get_default_campaign(coupon2, "25") source1 = seed_source(coupon1) source2 = seed_source(coupon1) source3 = seed_source(coupon1) source4 = seed_source(coupon2) creator.create_order(source1) creator.create_order(source2) creator.create_order(source3) creator.create_order(source4) # pay orders [o.create_payment(o.taxful_total_price) for o in Order.objects.all()] data = { "report": CouponsUsageReport.get_name(), "shop": shop.pk, "date_range": DateRangeChoices.ALL_TIME, "writer": "json", "force_download": 1, } report = CouponsUsageReport(**data) writer = get_writer_instance(data["writer"]) response = writer.get_response(report=report) if hasattr(response, "render"): response.render() json_data = json.loads(response.content.decode("utf-8")) assert force_text(CouponsUsageReport.title) in json_data.get("heading") data = json_data.get("tables")[0].get("data") assert len(data) == Order.objects.count() expected_data = [] orders = Order.objects.all().order_by("order_date") for order in orders: discount = order.shop.create_price(0) for dt in order.lines.discounts(): discount += dt.taxful_price expected_data.append({ "date": format_date(order.order_date, locale=get_current_babel_locale()), "coupon": order.codes[0], "order": str(order), "taxful_total": str(order.taxful_total_price.as_rounded().value), "taxful_subtotal": str((order.taxful_total_price - discount).as_rounded().value), "total_discount": str(discount.as_rounded().value) }) assert len(expected_data) == len(data) for ix, d in enumerate(data): for k, v in d.items(): assert expected_data[ix][k] == v
def get_bar_graph_datas(self): data = [] today = datetime.strptime(str(fields.Date.context_today(self)), DF) data.append({'label': _('Past'), 'value': 0.0, 'type': 'past'}) day_of_week = int( format_datetime(today, 'e', locale=self._context.get('lang') or 'en_US')) first_day_of_week = today + timedelta(days=-day_of_week + 1) for i in range(-1, 4): if i == 0: label = _('This Week') elif i == 3: label = _('Future') else: start_week = first_day_of_week + timedelta(days=i * 7) end_week = start_week + timedelta(days=6) if start_week.month == end_week.month: label = \ str(start_week.day) + '-' + str(end_week.day) + ' ' + \ format_date(end_week, 'MMM', locale=self._context.get( 'lang') or 'en_US') else: label = \ format_date(start_week, 'd MMM', locale=self._context.get('lang') or 'en_US' ) + '-' + format_date( end_week, 'd MMM', locale=self._context.get('lang') or'en_US') data.append({ 'label': label, 'value': 0.0, 'type': 'past' if i < 0 else 'future' }) select_sql_clause = 'SELECT count(*) FROM helpdesk_ticket AS h ' \ 'WHERE team_id = %(team_id)s' query_args = {'team_id': self.id} query = '' start_date = (first_day_of_week + timedelta(days=-7)) for i in range(0, 6): if i == 0: query += "(" + select_sql_clause + " and start_date < '" + \ start_date.strftime(DF) + "')" elif i == 5: query += " UNION ALL (" + select_sql_clause + \ " and start_date >= '" + \ start_date.strftime(DF) + "')" else: next_date = start_date + timedelta(days=7) query += " UNION ALL (" + select_sql_clause + \ " and start_date >= '" + start_date.strftime(DF) + \ "' and start_date < '" + next_date.strftime(DF) + \ "')" start_date = next_date self.env.cr.execute(query, query_args) query_results = self.env.cr.dictfetchall() for index in range(0, len(query_results)): if query_results[index]: data[index]['value'] = query_results[index].get('count') return [{'values': data}]
def make_html_files(self, actual_videos_ids): """ make up HTML structure to read the content /home.html Homepage for each video: - <slug-title>.html HTML article - videos/<videoId>/video.<ext> video file - videos/<videoId>/video.<lang>.vtt subtititle(s) - videos/<videoId>/video.jpg template """ def is_present(video): """ whether this video has actually been succeffuly downloaded """ return video["contentDetails"]["videoId"] in actual_videos_ids def get_subtitles(video_id): video_dir = self.videos_dir.joinpath(video_id) languages = [ x.stem.split(".")[1] for x in video_dir.iterdir() if x.is_file() and x.name.endswith(".vtt") ] return [get_language_details(language) for language in languages] env = jinja2.Environment(loader=jinja2.FileSystemLoader( str(self.templates_dir)), autoescape=True) videos = load_json(self.cache_dir, "videos").values() # filter videos so we only include the ones we could retrieve videos = list(filter(is_present, videos)) videos_channels = load_json(self.cache_dir, "videos_channels") for video in videos: video_id = video["contentDetails"]["videoId"] title = video["snippet"]["title"] slug = get_slug(title) description = video["snippet"]["description"] publication_date = dt_parser.parse( video["contentDetails"]["videoPublishedAt"]) author = videos_channels[video_id] subtitles = get_subtitles(video_id) video_url = f"https://www.youtube.com/watch?v={video_id}" html = env.get_template("article.html").render( video_id=video_id, video_format=self.video_format, author=author, title=title, description=description, date=format_date(publication_date, format="medium", locale=self.locale), subtitles=subtitles, url=video_url, channel_id=video["snippet"]["channelId"], color=self.main_color, background_color=self.secondary_color, autoplay=self.autoplay, ) with open(self.build_dir.joinpath(f"{slug}.html"), "w", encoding="utf-8") as fp: fp.write(html) # build homepage html = env.get_template("home.html").render( playlists=self.playlists, video_format=self.video_format, title=self.title, description=self.description, color=self.main_color, background_color=self.secondary_color, page_label=_("Page {current}/{total}"), back_label=_("Back to top"), ) with open(self.build_dir.joinpath("home.html"), "w", encoding="utf-8") as fp: fp.write(html) # rewrite app.js including `format` with open(self.assets_dir.joinpath("app.js"), "w", encoding="utf-8") as fp: fp.write( env.get_template("assets/app.js").render( video_format=self.video_format)) # rewrite app.js including `pagination` with open(self.assets_dir.joinpath("db.js"), "w", encoding="utf-8") as fp: fp.write( env.get_template("assets/db.js").render( NB_VIDEOS_PER_PAGE=self.nb_videos_per_page)) # write list of videos in data.js def to_data_js(video): return { "id": video["contentDetails"]["videoId"], "title": video["snippet"]["title"], "slug": get_slug(video["snippet"]["title"]), "description": video["snippet"]["description"], "subtitles": get_subtitles(video["contentDetails"]["videoId"]), "thumbnail": str( Path("videos").joinpath(video["contentDetails"]["videoId"], "video.jpg")), } with open(self.assets_dir.joinpath("data.js"), "w", encoding="utf-8") as fp: # write all playlists as they are for playlist in self.playlists: # retrieve list of videos for PL playlist_videos = load_json( self.cache_dir, f"playlist_{playlist.playlist_id}_videos") # filtering-out missing ones (deleted or not downloaded) playlist_videos = list( filter(skip_deleted_videos, playlist_videos)) playlist_videos = list(filter(is_present, playlist_videos)) # sorting them based on playlist playlist_videos.sort(key=lambda v: v["snippet"]["position"]) fp.write("var json_{slug} = {json_str};\n".format( slug=playlist.slug, json_str=json.dumps(list(map(to_data_js, playlist_videos)), indent=4), )) # write a metadata.json file with some content-related data with open(self.build_dir.joinpath("metadata.json"), "w", encoding="utf-8") as fp: json.dump({"video_format": self.video_format}, fp, indent=4)
def greek_date(self): return format_date(self.date, locale='el_GR')
def sync(self): user = ds_util.client.get(self.service.key.parent) if not user['preferences']['daily_weight_notif']: logging.debug( 'WeightTrendWorker: daily_weight_notif: not enabled: %s, %s', user.key, self.event.key, ) return to_imperial = user['preferences']['units'] == Preferences.Units.IMPERIAL # Calculate the trend. series_entity = Series.get(self.service.key) weight_trend = self._weight_trend(series_entity) time_frame = self._get_best_time_frame(weight_trend) if time_frame is None: logging.debug( 'WeightTrendWorker: daily_weight_notif: no timeframe: %s: %s', user.key, self.event.key, ) return if 'latest' not in weight_trend: logging.debug( 'WeightTrendWorker: daily_weight_notif: no latest: %s: %s', user.key, self.event.key, ) return latest_weight = weight_trend['latest']['weight'] if to_imperial: latest_weight = Weight(kg=latest_weight).lb time_frame_weight = weight_trend[time_frame]['weight'] if to_imperial: time_frame_weight = Weight(kg=time_frame_weight).lb time_frame_date = weight_trend[time_frame]['date'] delta = round(latest_weight - time_frame_weight, 1) unit = 'kg' if to_imperial: unit = 'lbs' if delta > 0: title = 'Up %.1f %s from %s' % (abs(delta), unit, time_frame) elif delta == 0: title = 'Weight unchanged since %s' % (time_frame,) else: title = 'Down %.1f %s from %s' % (abs(delta), unit, time_frame) body = 'You were %.1f %s on %s' % ( time_frame_weight, unit, format_date(time_frame_date.date(), format='medium'), ) # Find the best clients to send the message to. clients = fcm_util.best_clients(user.key) # Send the messages def notif_fn(client=None): return messaging.Message( notification=messaging.Notification(title=title, body=body), data={'refresh': 'weight'}, android=messaging.AndroidConfig( priority='high', # Wake up the device to notify. ttl=82800, # 23 hours # notification=messaging.AndroidNotification(), ), token=client['token'], ) fcm_util.send(self.event.key, clients, notif_fn)
def human_friendly_date_fr(value: str): if len(value) == 10: my_date = parser.parse(value) return format_date(my_date, 'medium', locale='fr_CA') else: return ""
def get_chart(self): if self.cached_chart is not None: return self.cached_chart chart_options = { "scales": { "yAxes": [{ "ticks": { "beginAtZero": True } }] } } today = date.today() chart_start_date = today - timedelta(days=365) orders = get_orders_for_shop(self.request) sum_sales_data = group_by_period(orders.valid().since( (today - chart_start_date).days), "order_date", "month", sum=Sum("taxful_total_price_value")) for (month, year) in month_iter(chart_start_date, today): sales_date = date(year, month, 1) if sales_date not in sum_sales_data: sum_sales_data[sales_date] = {"sum": Decimal(0)} # sort and recreated the ordered dict since we've put new items into sum_sales_data = OrderedDict( sorted(six.iteritems(sum_sales_data), key=lambda x: x[0])) locale = get_current_babel_locale() labels = [ format_date(k, format=get_year_and_month_format(locale), locale=locale) for k in sum_sales_data ] mixed_chart = MixedChart(title=_("Sales per Month (past 12 months)"), labels=labels, data_type=ChartDataType.CURRENCY, options=chart_options, currency=self.currency, locale=locale) cumulative_sales = [] average_sales = [] # only calculate cumulative and average if there are at least 3 months if len(sum_sales_data) >= 3: count = 0 total = Decimal() for month_sale in sum_sales_data.values(): total = total + month_sale["sum"] cumulative_sales.append(total) average_sales.append(total / (count + 1)) count = count + 1 # this will be on top of all bars if average_sales: mixed_chart.add_data(_("Average Sales"), [v for v in average_sales], ChartType.LINE) # this will be under the cummulative bars mixed_chart.add_data(_("Sales"), [v["sum"] for v in sum_sales_data.values()], ChartType.BAR) # this will be under all others charts if cumulative_sales: mixed_chart.add_data(_("Cumulative Total Sales"), [v for v in cumulative_sales], ChartType.BAR) self.cached_chart = mixed_chart return mixed_chart
def render_to_fragment(self, request, course_id, user_access, **kwargs): """ Renders a course message fragment for the specified course. """ course_key = CourseKey.from_string(course_id) course = get_course_with_access(request.user, 'load', course_key) # Get time until the start date, if already started, or no start date, value will be zero or negative now = datetime.now(UTC) already_started = course.start and now > course.start days_until_start_string = "started" if already_started else format_timedelta( course.start - now, locale=to_locale(get_language())) course_start_data = { 'course_start_date': format_date(course.start, locale=to_locale(get_language())), 'already_started': already_started, 'days_until_start_string': days_until_start_string } # Register the course home messages to be loaded on the page _register_course_home_messages(request, course, user_access, course_start_data) # Register course date alerts for course_date_block in get_course_date_blocks(course, request.user): course_date_block.register_alerts(request, course) # Register a course goal message, if appropriate # Only show the set course goal message for enrolled, unverified # users that have not yet set a goal in a course that allows for # verified statuses. user_goal = get_course_goal(auth.get_user(request), course_key) is_already_verified = CourseEnrollment.is_enrolled_as_verified( request.user, course_key) if has_course_goal_permission( request, course_id, user_access) and not is_already_verified and not user_goal: _register_course_goal_message(request, course) # Grab the relevant messages course_home_messages = list(CourseHomeMessages.user_messages(request)) # Pass in the url used to set a course goal goal_api_url = get_goal_api_url(request) # Grab the logo image_src = 'course_experience/images/home_message_author.png' context = { 'course_home_messages': course_home_messages, 'goal_api_url': goal_api_url, 'image_src': image_src, 'course_id': course_id, 'username': request.user.username, } html = render_to_string( 'course_experience/course-messages-fragment.html', context) return Fragment(html)
def format_date(self, date=None, format='medium'): return dates.format_date(date, format, locale=self.locale)
def get_bar_graph_datas(self): data = [] today = fields.Datetime.now(self) data.append({'label': _('Due'), 'value': 0.0, 'type': 'past'}) day_of_week = int( format_datetime(today, 'e', locale=get_lang(self.env).code)) first_day_of_week = today + timedelta(days=-day_of_week + 1) for i in range(-1, 4): if i == 0: label = _('This Week') elif i == 3: label = _('Not Due') else: start_week = first_day_of_week + timedelta(days=i * 7) end_week = start_week + timedelta(days=6) if start_week.month == end_week.month: label = str(start_week.day) + '-' + str( end_week.day) + ' ' + format_date( end_week, 'MMM', locale=get_lang(self.env).code) else: label = format_date( start_week, 'd MMM', locale=get_lang(self.env).code) + '-' + format_date( end_week, 'd MMM', locale=get_lang(self.env).code) data.append({ 'label': label, 'value': 0.0, 'type': 'past' if i < 0 else 'future' }) # Build SQL query to find amount aggregated by week (select_sql_clause, query_args) = self._get_bar_graph_select_query() query = '' start_date = (first_day_of_week + timedelta(days=-7)) for i in range(0, 6): if i == 0: query += "(" + select_sql_clause + " and invoice_date_due < '" + start_date.strftime( DF) + "')" elif i == 5: query += " UNION ALL (" + select_sql_clause + " and invoice_date_due >= '" + start_date.strftime( DF) + "')" else: next_date = start_date + timedelta(days=7) query += " UNION ALL (" + select_sql_clause + " and invoice_date_due >= '" + start_date.strftime( DF) + "' and invoice_date_due < '" + next_date.strftime( DF) + "')" start_date = next_date self.env.cr.execute(query, query_args) query_results = self.env.cr.dictfetchall() is_sample_data = True for index in range(0, len(query_results)): if query_results[index].get('aggr_date') != None: is_sample_data = False data[index]['value'] = query_results[index].get('total') [graph_title, graph_key] = self._graph_title_and_key() if is_sample_data: for index in range(0, len(query_results)): data[index]['type'] = 'o_sample_data' # we use unrealistic values for the sample data data[index]['value'] = random.randint(0, 20) graph_key = _('Sample data') return [{ 'values': data, 'title': graph_title, 'key': graph_key, 'is_sample_data': is_sample_data }]
def POST_update_pay(self, form, jquery, link, campaign, customer_id, pay_id, edit, address, creditcard): if not g.authorizenetapi: return if not link or not campaign or link._id != campaign.link_id: return abort(404, 'not found') # Check inventory if campaign_has_oversold_error(form, campaign): return # check the campaign dates are still valid (user may have created # the campaign a few days ago) min_start, max_start, max_end = promote.get_date_limits( link, c.user_is_sponsor) if campaign.start_date.date() > max_start: msg = _("please change campaign start date to %(date)s or earlier") date = format_date(max_start, format="short", locale=c.locale) msg %= {'date': date} form.set_text(".status", msg) return if campaign.start_date.date() < min_start: msg = _("please change campaign start date to %(date)s or later") date = format_date(min_start, format="short", locale=c.locale) msg %= {'date': date} form.set_text(".status", msg) return new_payment = not pay_id address_modified = new_payment or edit if address_modified: address_fields = [ "firstName", "lastName", "company", "address", "city", "state", "zip", "country", "phoneNumber" ] card_fields = ["cardNumber", "expirationDate", "cardCode"] if (form.has_errors(address_fields, errors.BAD_ADDRESS) or form.has_errors(card_fields, errors.BAD_CARD)): return pay_id = edit_profile(c.user, address, creditcard, pay_id) if pay_id: promote.new_payment_method(user=c.user, ip=request.ip, address=address, link=link) if pay_id: success, reason = promote.auth_campaign(link, campaign, c.user, pay_id) if success: hooks.get_hook("promote.campaign_paid").call(link=link, campaign=campaign) if not address and g.authorizenetapi: profiles = get_account_info(c.user).paymentProfiles profile = { p.customerPaymentProfileId: p for p in profiles }[pay_id] address = profile.billTo promote.successful_payment(link, campaign, request.ip, address) jquery.payment_redirect(promote.promo_edit_url(link), new_payment, campaign.bid) return else: promote.failed_payment_method(c.user, link) msg = reason or _("failed to authenticate card. sorry.") form.set_text(".status", msg) else: promote.failed_payment_method(c.user, link) form.set_text(".status", _("failed to authenticate card. sorry."))
def format_date_localized(self, dt): """Formats a datetime object to a localized human-readable string based on the current locale containing only the date.""" return format_date(dt, locale=self.__get_env_language_for_babel())
def update(self): self.data.update() waste_data = self.data.data try: if waste_data: if self.type in waste_data: collection_date = datetime.strptime( waste_data[self.type], "%Y-%m-%d").date() # Date in date format "%Y-%m-%d" self._year_month_day_date = str(collection_date) if collection_date: # Set the values of the sensor self._last_update = datetime.today().strftime( "%d-%m-%Y %H:%M") # Is the collection date today? self._is_collection_date_today = date.today( ) == collection_date # Days until collection date delta = collection_date - date.today() self._days_until_collection_date = delta.days # Only show the value if the date is lesser than or equal to (today + timespan_in_days) if collection_date <= date.today() + relativedelta( days=int(self.timespan_in_days)): # if the date does not contain a named day or month, return the date as normal if (self.date_format.find("a") == -1 and self.date_format.find("A") == -1 and self.date_format.find("b") == -1 and self.date_format.find("B") == -1): self._state = collection_date.strftime( self.date_format) # else convert the named values to the locale names else: edited_date_format = self.date_format.replace( "%a", "EEE") edited_date_format = edited_date_format.replace( "%A", "EEEE") edited_date_format = edited_date_format.replace( "%b", "MMM") edited_date_format = edited_date_format.replace( "%B", "MMMM") # half babel, half date string... something like EEEE 04-MMMM-2020 half_babel_half_date = collection_date.strftime( edited_date_format) # replace the digits with qquoted digits 01 --> '01' half_babel_half_date = re.sub( r"(\d+)", r"'\1'", half_babel_half_date) # transform the EEE, EEEE etc... to a real locale date, with babel locale_date = format_date( collection_date, half_babel_half_date, locale=self.locale, ) self._state = locale_date else: self._hidden = True else: raise ValueError() else: raise ValueError() else: raise ValueError() except ValueError: self._state = None self._hidden = True self._days_until_collection_date = None self._year_month_day_date = None self._is_collection_date_today = False self._last_update = datetime.today().strftime("%d-%m-%Y %H:%M")
def _get_graph(self): def get_week_name(start_date, locale): """ Generates a week name (string) from a datetime according to the locale: E.g.: locale start_date (datetime) return string "en_US" November 16th "16-22 Nov" "en_US" December 28th "28 Dec-3 Jan" """ if (start_date + relativedelta(days=6)).month == start_date.month: short_name_from = format_date(start_date, 'd', locale=locale) else: short_name_from = format_date(start_date, 'd MMM', locale=locale) short_name_to = format_date(start_date + relativedelta(days=6), 'd MMM', locale=locale) return short_name_from + '-' + short_name_to self.ensure_one() values = [] today = fields.Date.from_string(fields.Date.context_today(self)) start_date, end_date = self._graph_get_dates(today) graph_data = self._graph_data(start_date, end_date) # line graphs and bar graphs require different labels if self.dashboard_graph_type == 'line': x_field = 'x' y_field = 'y' else: x_field = 'label' y_field = 'value' # generate all required x_fields and update the y_values where we have data for them locale = self._context.get('lang') or 'en_US' if self.dashboard_graph_group == 'day': for day in range(0, (end_date - start_date).days + 1): short_name = format_date(start_date + relativedelta(days=day), 'd MMM', locale=locale) values.append({x_field: short_name, y_field: 0}) for data_item in graph_data: index = (datetime.strptime(data_item.get('x_value'), DF).date() - start_date).days values[index][y_field] = data_item.get('y_value') elif self.dashboard_graph_group == 'week': weeks_in_start_year = int(date(start_date.year, 12, 28).isocalendar()[1]) # This date is always in the last week of ISO years for week in range(0, (end_date.isocalendar()[1] - start_date.isocalendar()[1]) % weeks_in_start_year + 1): short_name = get_week_name(start_date + relativedelta(days=7 * week), locale) values.append({x_field: short_name, y_field: 0}) for data_item in graph_data: index = int((data_item.get('x_value') - start_date.isocalendar()[1]) % weeks_in_start_year) values[index][y_field] = data_item.get('y_value') elif self.dashboard_graph_group == 'month': for month in range(0, (end_date.month - start_date.month) % 12 + 1): short_name = format_date(start_date + relativedelta(months=month), 'MMM', locale=locale) values.append({x_field: short_name, y_field: 0}) for data_item in graph_data: index = int((data_item.get('x_value') - start_date.month) % 12) values[index][y_field] = data_item.get('y_value') elif self.dashboard_graph_group == 'user': for data_item in graph_data: values.append({x_field: self.env['res.users'].browse(data_item.get('x_value')).name or _('Not Defined'), y_field: data_item.get('y_value')}) else: for data_item in graph_data: values.append({x_field: data_item.get('x_value'), y_field: data_item.get('y_value')}) [graph_title, graph_key] = self._graph_title_and_key() color = '#875A7B' if '+e' in version else '#7c7bad' return [{'values': values, 'area': True, 'title': graph_title, 'key': graph_key, 'color': color}]