Python babel.dates.format_date() Examples

The following are 18 code examples of babel.dates.format_date(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module babel.dates , or try the search function .
Example #1
Source File: calendar_.py    From tkcalendar with GNU General Public License v3.0 6 votes vote down vote up
def _textvariable_trace(self, *args):
        """Connect StringVar value with selected date."""
        if self._properties.get("selectmode") == "day":
            date = self._textvariable.get()
            if not date:
                self._remove_selection()
                self._sel_date = None
            else:
                try:
                    self._sel_date = self.parse_date(date)
                except Exception:
                    if self._sel_date is None:
                        self._textvariable.set('')
                    else:
                        self._textvariable.set(self.format_date(self._sel_date))
                    raise ValueError("%r is not a valid date." % date)
                else:
                    self._date = self._sel_date.replace(day=1)
                    self._display_calendar()
                    self._display_selection() 
Example #2
Source File: calendar_.py    From tkcalendar with GNU General Public License v3.0 6 votes vote down vote up
def _on_click(self, event):
        """Select the day on which the user clicked."""
        if self._properties['state'] == 'normal':
            label = event.widget
            if "disabled" not in label.state():
                day = label.cget("text")
                style = label.cget("style")
                if style in ['normal_om.%s.TLabel' % self._style_prefixe, 'we_om.%s.TLabel' % self._style_prefixe]:
                    if label in self._calendar[0]:
                        self._prev_month()
                    else:
                        self._next_month()
                if day:
                    day = int(day)
                    year, month = self._date.year, self._date.month
                    self._remove_selection()
                    self._sel_date = self.date(year, month, day)
                    self._display_selection()
                    if self._textvariable is not None:
                        self._textvariable.set(self.format_date(self._sel_date))
                    self.event_generate("<<CalendarSelected>>") 
Example #3
Source File: format.py    From xlsx2html with MIT License 5 votes vote down vote up
def format_cell(cell, locale=None, f_cell=None):
    value = cell.value
    formatted_value = value or '&nbsp;'
    number_format = cell.number_format
    if not number_format:
        return format_hyperlink(formatted_value, cell.hyperlink)

    if isinstance(value, six.integer_types) or isinstance(value, float):
        if number_format.lower() != 'general':
            locale = locale or LC_NUMERIC
            formatted_value = format_decimal(value, number_format, locale=locale)

    locale = locale or LC_TIME

    # Possible problem with dd-mmm and more
    number_format = FIX_BUILTIN_FORMATS.get(cell._style.numFmtId, number_format)
    number_format = number_format.split(';')[0]

    if type(value) == datetime.date:
        formatted_value = format_date(value, number_format, locale=locale)
    elif type(value) == datetime.datetime:
        formatted_value = format_datetime(value, number_format, locale=locale)
    elif type(value) == datetime.time:
        formatted_value = format_time(value, number_format, locale=locale)
    if cell.hyperlink:
        return format_hyperlink(formatted_value, cell)
    return formatted_value 
Example #4
Source File: jinjia.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def formatdate_filter(val):
    try:
        conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', val)
        formatdate = datetime.datetime.strptime(conformed_timestamp[:15], "%Y%m%d %H%M%S")
        return format_date(formatdate, format='medium', locale=get_locale())
    except AttributeError as e:
        log.error('Babel error: %s, Current user locale: %s, Current User: %s', e,
                  current_user.locale,
                  current_user.nickname
                  )
        return formatdate 
Example #5
Source File: format.py    From xlsx2html with MIT License 5 votes vote down vote up
def format_date(date, fmt, locale=LC_TIME):
    fmt = normalize_date_format(fmt)
    return babel_dates.format_date(date, fmt, locale) 
Example #6
Source File: utils.py    From personfinder with Apache License 2.0 5 votes vote down vote up
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()); 
Example #7
Source File: views.py    From memorious with MIT License 5 votes vote down vote up
def date_filter(s):
    if s is None or s == 0 or not len(str(s)):
        return ''
    return format_date(s, locale='en_GB', format='short') 
Example #8
Source File: calendar_.py    From tkcalendar with GNU General Public License v3.0 5 votes vote down vote up
def get_date(self):
        """Return selected date as string."""
        if self._sel_date is not None:
            return self.format_date(self._sel_date)
        else:
            return ""

    # --- events 
Example #9
Source File: calendar_.py    From tkcalendar with GNU General Public License v3.0 5 votes vote down vote up
def selection_set(self, date):
        """
        Set the selection to date.

            date : datetime.date, datetime.datetime or str
                    date to be made visible. If given as a string, it should be
                    in the format corresponding to the calendar locale.

        Do nothing if selectmode == "none".
        """
        if self._properties.get("selectmode") == "day" and self._properties['state'] == 'normal':
            if date is None:
                self.selection_clear()
            else:
                if isinstance(date, self.datetime):
                    self._sel_date = date.date()
                elif isinstance(date, self.date):
                    self._sel_date = date
                else:
                    try:
                        self._sel_date = self.parse_date(date)
                    except Exception as e:
                        raise ValueError("%r is not a valid date." % date)
                if self['mindate'] is not None and self._sel_date < self['mindate']:
                    self._sel_date = self['mindate']
                elif self['maxdate'] is not None and self._sel_date > self['maxdate']:
                    self._sel_date = self['maxdate']
                if self._textvariable is not None:
                    self._textvariable.set(self.format_date(self._sel_date))

                self._date = self._sel_date.replace(day=1)
                self._display_calendar()
                self._display_selection()
                self._btns_date_range() 
Example #10
Source File: calendar_.py    From tkcalendar with GNU General Public License v3.0 5 votes vote down vote up
def format_date(self, date=None):
        """Convert date (datetime.date) to a string in the locale."""
        return format_date(date, self._properties['date_pattern'], self._properties['locale']) 
Example #11
Source File: generate.py    From keras-attention with GNU Affero General Public License v3.0 5 votes vote down vote up
def create_date():
    """
        Creates some fake dates 
        :returns: tuple containing 
                  1. human formatted string
                  2. machine formatted string
                  3. date object.
    """
    dt = fake.date_object()

    # wrapping this in a try catch because
    # the locale 'vo' and format 'full' will fail
    try:
        human = format_date(dt,
                            format=random.choice(FORMATS),
                            locale=random.choice(LOCALES))

        case_change = random.randint(0,3) # 1/2 chance of case change
        if case_change == 1:
            human = human.upper()
        elif case_change == 2:
            human = human.lower()

        machine = dt.isoformat()
    except AttributeError as e:
        # print(e)
        return None, None, None

    return human, machine, dt 
Example #12
Source File: columns.py    From flask_table with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def td_format(self, content):
        if content:
            return format_date(content, self.date_format)
        else:
            return '' 
Example #13
Source File: i18n.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
def format_date(date=None, format=None, rebase=True):
    """See :meth:`I18n.format_date`."""
    return get_i18n().format_date(date, format, rebase) 
Example #14
Source File: i18n.py    From googleapps-message-recall with Apache License 2.0 5 votes vote down vote up
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) 
Example #15
Source File: emails.py    From karrot-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def prepare_activity_conversation_message_notification(user, messages):
    activity = target_from_messages(messages)
    language = language_for_user(user)
    with translation.override(language):
        with timezone.override(activity.place.group.timezone):
            weekday = format_date(
                activity.date.start.astimezone(timezone.get_current_timezone()),
                'EEEE',
                locale=translation.to_locale(language),
            )
            time = format_time(
                activity.date.start,
                format='short',
                locale=translation.to_locale(language),
                tzinfo=timezone.get_current_timezone(),
            )
            date = format_date(
                activity.date.start.astimezone(timezone.get_current_timezone()),
                format='long',
                locale=translation.to_locale(language),
            )

            long_date = '{} {}, {}'.format(weekday, time, date)
            short_date = '{} {}'.format(weekday, time)

            reply_to_name = _('Pickup %(date)s') % {
                'date': short_date,
            }
            conversation_name = _('Pickup %(date)s') % {
                'date': long_date,
            }

        return prepare_message_notification(
            user,
            messages,
            group=activity.place.group,
            reply_to_name=reply_to_name,
            conversation_name=conversation_name,
            conversation_url=activity_detail_url(activity),
            stats_category='activity_conversation_message'
        ) 
Example #16
Source File: email_utils.py    From karrot-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def date_filter(value):
    return format_date(
        value.astimezone(get_current_timezone()),
        format='full',
        locale=to_locale(get_language()),
    ) 
Example #17
Source File: lobby_parser.py    From yugioh-game with MIT License 4 votes vote down vote up
def finger(caller):

	pl = caller.connection.player
	session = pl.connection.session

	name = caller.args[0]
	name = name[0].upper()+name[1:].lower()
	
	fp = globals.server.get_player(name)
	
	if fp is None:
		account = session.query(models.Account).filter_by(name=name).first()
		if account is None:
			pl.notify(pl._("No player with that name found."))
			return
	else:
		account = fp.get_account(session)

	pl.notify(pl._("Finger report for %s")%(account.name))

	pl.notify(pl._("Created on %s")%(format_date(account.created, format='medium', locale=pl.get_locale())))

	if fp is not None:
		pl.notify(pl._("Currently logged in"))
	else:
		pl.notify(pl._("Last logged in on %s")%(format_date(account.last_logged_in, format='medium', locale=pl.get_locale())))

	stats = account.statistics

	stats = natsort.natsorted(stats, key=lambda s: s.opponent.name)

	if len(stats) == 0:
		return

	pl.notify(pl._("Duel statistics:"))

	for stat in stats:

		pl.notify(pl._("%s - Won: %d, Lost: %d, Drawn: %d, Surrendered: %d")%(stat.opponent.name, stat.win, stat.lose, stat.draw, stat.giveup))

	won = sum([s.win for s in stats])
	lost = sum([s.lose for s in stats])
	drawn = sum([s.draw for s in stats])
	surrendered = sum([s.giveup for s in stats])

	pl.notify(pl._("Conclusion - Won: %d, Lost: %d, Drawn: %d, Surrendered: %d")%(won, lost, drawn, surrendered))

	if won+lost > 0:
		average = float(won)*100/(float(won)+float(lost))

		pl.notify(pl._("%.2f%% Success.")%(average)) 
Example #18
Source File: fb2cal.py    From fb2cal with GNU General Public License v3.0 4 votes vote down vote up
def get_day_name_offset_dict(user_locale):
    """ The day name to offset dict maps a day name to a numerical day offset which can be used to add days to the current date.
        Day names will match the provided user locale and will be in lowercase.
    """

    offset_dict = {}

    # Todays birthdays will be shown normally (as a date) so start from tomorrow
    start_date = datetime.now() + relativedelta(days=1)

    # Method 1: Babel
    try:
        babel_locale = Locale.parse(user_locale, sep='_')
        cur_date = start_date

        # Iterate through the following 7 days
        for i in range(1, 8):
            offset_dict[format_date(cur_date, 'EEEE', locale=babel_locale).lower()] = i
            cur_date = cur_date + relativedelta(days=1)

        return offset_dict
    except UnknownLocaleError as e:
        logger.debug(f'Babel UnknownLocaleError: {e}')

    # Method 2: System locale
    cur_date = start_date
    locale_check_list = [user_locale, user_locale + 'UTF-8', user_locale + 'utf-8']
    system_locale = None

    # Windows
    if any(platform.win32_ver()):
        for locale_to_check in locale_check_list:
            if locale_to_check in locale.windows_locale.values():
                system_locale = locale_to_check
                break
    # POSIX
    else:
        for locale_to_check in locale_check_list:
            if locale_to_check in locale.locale_alias.values():
                system_locale = locale_to_check
                break

    # Check if system locale was found
    if system_locale:
        locale.setlocale(locale.LC_ALL, system_locale)

        # Iterate through the following 7 days
        for i in range(1, 8):
            offset_dict[cur_date.strftime('%A').lower()] = i
            cur_date = cur_date + relativedelta(days=1)

        return offset_dict
    else:
        logger.debug(f"Unable to find system locale for provided user locale: '{user_locale}'")

    # Failure
    logger.error(f"Failed to generate day name offset dictionary for provided user locale: '{user_locale}'")
    raise SystemError