babel package

Submodules

babel.core module

babel.core

Core locale representation and locale data access.

copyright:
  1. 2013 by the Babel Team.
license:

BSD, see LICENSE for more details.

exception babel.core.UnknownLocaleError(identifier)[source]

Bases: exceptions.Exception

Exception thrown when a locale is requested for which no locale data is available.

identifier = None

The identifier of the locale that could not be found.

class babel.core.Locale(language, territory=None, script=None, variant=None)[source]

Bases: object

Representation of a specific locale.

>>> locale = Locale('en', 'US')
>>> repr(locale)
"Locale('en', territory='US')"
>>> locale.display_name
u'English (United States)'

A Locale object can also be instantiated from a raw locale string:

>>> locale = Locale.parse('en-US', sep='-')
>>> repr(locale)
"Locale('en', territory='US')"

Locale objects provide access to a collection of locale data, such as territory and language names, number and date format patterns, and more:

>>> locale.number_symbols['decimal']
u'.'

If a locale is requested for which no locale data is available, an UnknownLocaleError is raised:

>>> Locale.parse('en_DE')
Traceback (most recent call last):
    ...
UnknownLocaleError: unknown locale 'en_DE'

For more information see RFC 3066.

currencies

Mapping of currency codes to translated currency names. This only returns the generic form of the currency name, not the count specific one. If an actual number is requested use the babel.numbers.get_currency_name() function.

>>> Locale('en').currencies['COP']
u'Colombian Peso'
>>> Locale('de', 'DE').currencies['COP']
u'Kolumbianischer Peso'
currency_formats

Locale patterns for currency number formatting.

>>> print Locale('en', 'US').currency_formats[None]
<NumberPattern u'\xa4#,##0.00'>
currency_symbols

Mapping of currency codes to symbols.

>>> Locale('en', 'US').currency_symbols['USD']
u'$'
>>> Locale('es', 'CO').currency_symbols['USD']
u'US$'
date_formats

Locale patterns for date formatting.

>>> Locale('en', 'US').date_formats['short']
<DateTimePattern u'M/d/yy'>
>>> Locale('fr', 'FR').date_formats['long']
<DateTimePattern u'd MMMM y'>
datetime_formats

Locale patterns for datetime formatting.

>>> Locale('en').datetime_formats['full']
u"{1} 'at' {0}"
>>> Locale('th').datetime_formats['medium']
u'{1}, {0}'
days

Locale display names for weekdays.

>>> Locale('de', 'DE').days['format']['wide'][3]
u'Donnerstag'
decimal_formats

Locale patterns for decimal number formatting.

>>> Locale('en', 'US').decimal_formats[None]
<NumberPattern u'#,##0.###'>
classmethod default(category=None, aliases={'el': 'el_GR', 'fi': 'fi_FI', 'bg': 'bg_BG', 'uk': 'uk_UA', 'tr': 'tr_TR', 'ca': 'ca_ES', 'de': 'de_DE', 'fr': 'fr_FR', 'da': 'da_DK', 'fa': 'fa_IR', 'ar': 'ar_SY', 'mk': 'mk_MK', 'bs': 'bs_BA', 'cs': 'cs_CZ', 'et': 'et_EE', 'gl': 'gl_ES', 'id': 'id_ID', 'es': 'es_ES', 'he': 'he_IL', 'ru': 'ru_RU', 'nl': 'nl_NL', 'pt': 'pt_PT', 'nn': 'nn_NO', 'no': 'nb_NO', 'ko': 'ko_KR', 'sv': 'sv_SE', 'km': 'km_KH', 'ja': 'ja_JP', 'lv': 'lv_LV', 'lt': 'lt_LT', 'en': 'en_US', 'sk': 'sk_SK', 'th': 'th_TH', 'sl': 'sl_SI', 'it': 'it_IT', 'hu': 'hu_HU', 'ro': 'ro_RO', 'is': 'is_IS', 'pl': 'pl_PL'})[source]

Return the system default locale for the specified category.

>>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LC_MESSAGES']:
...     os.environ[name] = ''
>>> os.environ['LANG'] = 'fr_FR.UTF-8'
>>> Locale.default('LC_MESSAGES')
Locale('fr', territory='FR')

The following fallbacks to the variable are always considered:

  • LANGUAGE
  • LC_ALL
  • LC_CTYPE
  • LANG
Parameters:
  • category – one of the LC_XXX environment variable names
  • aliases – a dictionary of aliases for locale identifiers
display_name

The localized display name of the locale.

>>> Locale('en').display_name
u'English'
>>> Locale('en', 'US').display_name
u'English (United States)'
>>> Locale('sv').display_name
u'svenska'
Type:unicode
english_name

The english display name of the locale.

>>> Locale('de').english_name
u'German'
>>> Locale('de', 'DE').english_name
u'German (Germany)'
Type:unicode
eras

Locale display names for eras.

>>> Locale('en', 'US').eras['wide'][1]
u'Anno Domini'
>>> Locale('en', 'US').eras['abbreviated'][0]
u'BC'
first_week_day

The first day of a week, with 0 being Monday.

>>> Locale('de', 'DE').first_week_day
0
>>> Locale('en', 'US').first_week_day
6
get_display_name(locale=None)[source]

Return the display name of the locale using the given locale.

The display name will include the language, territory, script, and variant, if those are specified.

>>> Locale('zh', 'CN', script='Hans').get_display_name('en')
u'Chinese (Simplified, China)'
Parameters:locale – the locale to use
get_language_name(locale=None)[source]

Return the language of this locale in the given locale.

>>> Locale('zh', 'CN', script='Hans').get_language_name('de')
u'Chinesisch'

New in version 1.0.

Parameters:locale – the locale to use
get_script_name(locale=None)[source]

Return the script name in the given locale.

get_territory_name(locale=None)[source]

Return the territory name in the given locale.

language = None

the language code

language_name

The localized language name of the locale.

>>> Locale('en', 'US').language_name
u'English'
languages

Mapping of language codes to translated language names.

>>> Locale('de', 'DE').languages['ja']
u'Japanisch'

See ISO 639 for more information.

meta_zones

Locale display names for meta time zones.

Meta time zones are basically groups of different Olson time zones that have the same GMT offset and daylight savings time.

>>> Locale('en', 'US').meta_zones['Europe_Central']['long']['daylight']
u'Central European Summer Time'

New in version 0.9.

min_week_days

The minimum number of days in a week so that the week is counted as the first week of a year or month.

>>> Locale('de', 'DE').min_week_days
4
months

Locale display names for months.

>>> Locale('de', 'DE').months['format']['wide'][10]
u'Oktober'
classmethod negotiate(preferred, available, sep='_', aliases={'el': 'el_GR', 'fi': 'fi_FI', 'bg': 'bg_BG', 'uk': 'uk_UA', 'tr': 'tr_TR', 'ca': 'ca_ES', 'de': 'de_DE', 'fr': 'fr_FR', 'da': 'da_DK', 'fa': 'fa_IR', 'ar': 'ar_SY', 'mk': 'mk_MK', 'bs': 'bs_BA', 'cs': 'cs_CZ', 'et': 'et_EE', 'gl': 'gl_ES', 'id': 'id_ID', 'es': 'es_ES', 'he': 'he_IL', 'ru': 'ru_RU', 'nl': 'nl_NL', 'pt': 'pt_PT', 'nn': 'nn_NO', 'no': 'nb_NO', 'ko': 'ko_KR', 'sv': 'sv_SE', 'km': 'km_KH', 'ja': 'ja_JP', 'lv': 'lv_LV', 'lt': 'lt_LT', 'en': 'en_US', 'sk': 'sk_SK', 'th': 'th_TH', 'sl': 'sl_SI', 'it': 'it_IT', 'hu': 'hu_HU', 'ro': 'ro_RO', 'is': 'is_IS', 'pl': 'pl_PL'})[source]

Find the best match between available and requested locale strings.

>>> Locale.negotiate(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
Locale('de', territory='DE')
>>> Locale.negotiate(['de_DE', 'en_US'], ['en', 'de'])
Locale('de')
>>> Locale.negotiate(['de_DE', 'de'], ['en_US'])

You can specify the character used in the locale identifiers to separate the differnet components. This separator is applied to both lists. Also, case is ignored in the comparison:

>>> Locale.negotiate(['de-DE', 'de'], ['en-us', 'de-de'], sep='-')
Locale('de', territory='DE')
Parameters:
  • preferred – the list of locale identifers preferred by the user
  • available – the list of locale identifiers available
  • aliases – a dictionary of aliases for locale identifiers
number_symbols

Symbols used in number formatting.

>>> Locale('fr', 'FR').number_symbols['decimal']
u','
classmethod parse(identifier, sep='_', resolve_likely_subtags=True)[source]

Create a Locale instance for the given locale identifier.

>>> l = Locale.parse('de-DE', sep='-')
>>> l.display_name
u'Deutsch (Deutschland)'

If the identifier parameter is not a string, but actually a Locale object, that object is returned:

>>> Locale.parse(l)
Locale('de', territory='DE')

This also can perform resolving of likely subtags which it does by default. This is for instance useful to figure out the most likely locale for a territory you can use 'und' as the language tag:

>>> Locale.parse('und_AT')
Locale('de', territory='AT')
Parameters:
  • identifier – the locale identifier string
  • sep – optional component separator
  • resolve_likely_subtags – if this is specified then a locale will have its likely subtag resolved if the locale otherwise does not exist. For instance zh_TW by itself is not a locale that exists but Babel can automatically expand it to the full form of zh_hant_TW. Note that this expansion is only taking place if no locale exists otherwise. For instance there is a locale en that can exist by itself.
Raises:
  • ValueError – if the string does not appear to be a valid locale identifier
  • UnknownLocaleError – if no locale data is available for the requested locale
percent_formats

Locale patterns for percent number formatting.

>>> Locale('en', 'US').percent_formats[None]
<NumberPattern u'#,##0%'>
periods

Locale display names for day periods (AM/PM).

>>> Locale('en', 'US').periods['am']
u'AM'
plural_form

Plural rules for the locale.

>>> Locale('en').plural_form(1)
'one'
>>> Locale('en').plural_form(0)
'other'
>>> Locale('fr').plural_form(0)
'one'
>>> Locale('ru').plural_form(100)
'many'
quarters

Locale display names for quarters.

>>> Locale('de', 'DE').quarters['format']['wide'][1]
u'1. Quartal'
scientific_formats

Locale patterns for scientific number formatting.

>>> Locale('en', 'US').scientific_formats[None]
<NumberPattern u'#E0'>
script = None

the script code

script_name

The localized script name of the locale if available.

>>> Locale('ms', 'SG', script='Latn').script_name
u'Latin'
scripts

Mapping of script codes to translated script names.

>>> Locale('en', 'US').scripts['Hira']
u'Hiragana'

See ISO 15924 for more information.

territories

Mapping of script codes to translated script names.

>>> Locale('es', 'CO').territories['DE']
u'Alemania'

See ISO 3166 for more information.

territory = None

the territory (country or region) code

territory_name

The localized territory name of the locale if available.

>>> Locale('de', 'DE').territory_name
u'Deutschland'
time_formats

Locale patterns for time formatting.

>>> Locale('en', 'US').time_formats['short']
<DateTimePattern u'h:mm a'>
>>> Locale('fr', 'FR').time_formats['long']
<DateTimePattern u'HH:mm:ss z'>
time_zones

Locale display names for time zones.

>>> Locale('en', 'US').time_zones['Europe/London']['long']['daylight']
u'British Summer Time'
>>> Locale('en', 'US').time_zones['America/St_Johns']['city']
u'St. John\u2019s'
variant = None

the variant code

variants

Mapping of script codes to translated script names.

>>> Locale('de', 'DE').variants['1901']
u'Alte deutsche Rechtschreibung'
weekend_end

The day the weekend ends, with 0 being Monday.

>>> Locale('de', 'DE').weekend_end
6
weekend_start

The day the weekend starts, with 0 being Monday.

>>> Locale('de', 'DE').weekend_start
5
zone_formats

Patterns related to the formatting of time zones.

>>> Locale('en', 'US').zone_formats['fallback']
u'%(1)s (%(0)s)'
>>> Locale('pt', 'BR').zone_formats['region']
u'Hor\xe1rio %s'

New in version 0.9.

babel.core.default_locale(category=None, aliases={'el': 'el_GR', 'fi': 'fi_FI', 'bg': 'bg_BG', 'uk': 'uk_UA', 'tr': 'tr_TR', 'ca': 'ca_ES', 'de': 'de_DE', 'fr': 'fr_FR', 'da': 'da_DK', 'fa': 'fa_IR', 'ar': 'ar_SY', 'mk': 'mk_MK', 'bs': 'bs_BA', 'cs': 'cs_CZ', 'et': 'et_EE', 'gl': 'gl_ES', 'id': 'id_ID', 'es': 'es_ES', 'he': 'he_IL', 'ru': 'ru_RU', 'nl': 'nl_NL', 'pt': 'pt_PT', 'nn': 'nn_NO', 'no': 'nb_NO', 'ko': 'ko_KR', 'sv': 'sv_SE', 'km': 'km_KH', 'ja': 'ja_JP', 'lv': 'lv_LV', 'lt': 'lt_LT', 'en': 'en_US', 'sk': 'sk_SK', 'th': 'th_TH', 'sl': 'sl_SI', 'it': 'it_IT', 'hu': 'hu_HU', 'ro': 'ro_RO', 'is': 'is_IS', 'pl': 'pl_PL'})[source]

Returns the system default locale for a given category, based on environment variables.

>>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE']:
...     os.environ[name] = ''
>>> os.environ['LANG'] = 'fr_FR.UTF-8'
>>> default_locale('LC_MESSAGES')
'fr_FR'

The “C” or “POSIX” pseudo-locales are treated as aliases for the “en_US_POSIX” locale:

>>> os.environ['LC_MESSAGES'] = 'POSIX'
>>> default_locale('LC_MESSAGES')
'en_US_POSIX'

The following fallbacks to the variable are always considered:

  • LANGUAGE
  • LC_ALL
  • LC_CTYPE
  • LANG
Parameters:
  • category – one of the LC_XXX environment variable names
  • aliases – a dictionary of aliases for locale identifiers
babel.core.negotiate_locale(preferred, available, sep='_', aliases={'el': 'el_GR', 'fi': 'fi_FI', 'bg': 'bg_BG', 'uk': 'uk_UA', 'tr': 'tr_TR', 'ca': 'ca_ES', 'de': 'de_DE', 'fr': 'fr_FR', 'da': 'da_DK', 'fa': 'fa_IR', 'ar': 'ar_SY', 'mk': 'mk_MK', 'bs': 'bs_BA', 'cs': 'cs_CZ', 'et': 'et_EE', 'gl': 'gl_ES', 'id': 'id_ID', 'es': 'es_ES', 'he': 'he_IL', 'ru': 'ru_RU', 'nl': 'nl_NL', 'pt': 'pt_PT', 'nn': 'nn_NO', 'no': 'nb_NO', 'ko': 'ko_KR', 'sv': 'sv_SE', 'km': 'km_KH', 'ja': 'ja_JP', 'lv': 'lv_LV', 'lt': 'lt_LT', 'en': 'en_US', 'sk': 'sk_SK', 'th': 'th_TH', 'sl': 'sl_SI', 'it': 'it_IT', 'hu': 'hu_HU', 'ro': 'ro_RO', 'is': 'is_IS', 'pl': 'pl_PL'})[source]

Find the best match between available and requested locale strings.

>>> negotiate_locale(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
'de_DE'
>>> negotiate_locale(['de_DE', 'en_US'], ['en', 'de'])
'de'

Case is ignored by the algorithm, the result uses the case of the preferred locale identifier:

>>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at'])
'de_DE'
>>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at'])
'de_DE'

By default, some web browsers unfortunately do not include the territory in the locale identifier for many locales, and some don’t even allow the user to easily add the territory. So while you may prefer using qualified locale identifiers in your web-application, they would not normally match the language-only locale sent by such browsers. To workaround that, this function uses a default mapping of commonly used langauge-only locale identifiers to identifiers including the territory:

>>> negotiate_locale(['ja', 'en_US'], ['ja_JP', 'en_US'])
'ja_JP'

Some browsers even use an incorrect or outdated language code, such as “no” for Norwegian, where the correct locale identifier would actually be “nb_NO” (Bokmål) or “nn_NO” (Nynorsk). The aliases are intended to take care of such cases, too:

>>> negotiate_locale(['no', 'sv'], ['nb_NO', 'sv_SE'])
'nb_NO'

You can override this default mapping by passing a different aliases dictionary to this function, or you can bypass the behavior althogher by setting the aliases parameter to None.

Parameters:
  • preferred – the list of locale strings preferred by the user
  • available – the list of locale strings available
  • sep – character that separates the different parts of the locale strings
  • aliases – a dictionary of aliases for locale identifiers
babel.core.parse_locale(identifier, sep='_')[source]

Parse a locale identifier into a tuple of the form (language, territory, script, variant).

>>> parse_locale('zh_CN')
('zh', 'CN', None, None)
>>> parse_locale('zh_Hans_CN')
('zh', 'CN', 'Hans', None)

The default component separator is “_”, but a different separator can be specified using the sep parameter:

>>> parse_locale('zh-CN', sep='-')
('zh', 'CN', None, None)

If the identifier cannot be parsed into a locale, a ValueError exception is raised:

>>> parse_locale('not_a_LOCALE_String')
Traceback (most recent call last):
  ...
ValueError: 'not_a_LOCALE_String' is not a valid locale identifier

Encoding information and locale modifiers are removed from the identifier:

>>> parse_locale('it_IT@euro')
('it', 'IT', None, None)
>>> parse_locale('en_US.UTF-8')
('en', 'US', None, None)
>>> parse_locale('de_DE.iso885915@euro')
('de', 'DE', None, None)

See RFC 4646 for more information.

Parameters:
  • identifier – the locale identifier string
  • sep – character that separates the different components of the locale identifier
Raises ValueError:
 

if the string does not appear to be a valid locale identifier

babel.dates module

babel.dates

Locale dependent formatting and parsing of dates and times.

The default locale for the functions in this module is determined by the following environment variables, in that order:

  • LC_TIME,
  • LC_ALL, and
  • LANG
copyright:
  1. 2013 by the Babel Team.
license:

BSD, see LICENSE for more details.

class babel.dates.DateTimeFormat(value, locale)[source]

Bases: object

format(value, length)[source]
format_day_of_week_in_month()[source]
format_day_of_year(num)[source]
format_era(char, num)[source]
format_frac_seconds(num)[source]
format_milliseconds_in_day(num)[source]
format_month(char, num)[source]
format_period(char)[source]
format_quarter(char, num)[source]
format_timezone(char, num)[source]
format_week(char, num)[source]
format_weekday(char, num)[source]
format_year(char, num)[source]
get_day_of_year(date=None)[source]
get_week_number(day_of_period, day_of_week=None)[source]

Return the number of the week of a day within a period. This may be the week number in a year or the week number in a month.

Usually this will return a value equal to or greater than 1, but if the first week of the period is so short that it actually counts as the last week of the previous period, this function will return 0.

>>> format = DateTimeFormat(date(2006, 1, 8), Locale.parse('de_DE'))
>>> format.get_week_number(6)
1
>>> format = DateTimeFormat(date(2006, 1, 8), Locale.parse('en_US'))
>>> format.get_week_number(6)
2
Parameters:
  • day_of_period – the number of the day in the period (usually either the day of month or the day of year)
  • day_of_week – the week day; if ommitted, the week day of the current date is assumed
class babel.dates.DateTimePattern(pattern, format)[source]

Bases: object

apply(datetime, locale)[source]
class babel.dates.TimezoneTransition(activates, from_tzinfo, to_tzinfo, reference_date=None)[source]

Bases: object

A helper object that represents the return value from get_next_timezone_transition().

activates = None

the time of the activation of the timezone transition in UTC.

from_offset

The UTC offset in seconds before the transition.

from_tz

The name of the timezone before the transition.

from_tzinfo = None

the timezone from where the transition starts.

reference_date = None

the reference date that was provided. This is the dt parameter to the get_next_timezone_transition().

to_offset

The UTC offset in seconds after the transition.

to_tz

The name of the timezone after the transition.

to_tzinfo = None

the timezone for after the transition.

babel.dates.format_date(date=None, format='medium', locale='en_US')[source]

Return a date formatted according to the given pattern.

>>> d = date(2007, 04, 01)
>>> format_date(d, locale='en_US')
u'Apr 1, 2007'
>>> format_date(d, format='full', locale='de_DE')
u'Sonntag, 1. April 2007'

If you don’t want to use the locale default formats, you can specify a custom date pattern:

>>> format_date(d, "EEE, MMM d, ''yy", locale='en')
u"Sun, Apr 1, '07"
Parameters:
  • date – the date or datetime object; if None, the current date is used
  • format – one of “full”, “long”, “medium”, or “short”, or a custom date/time pattern
  • locale – a Locale object or a locale identifier
babel.dates.format_datetime(datetime=None, format='medium', tzinfo=None, locale='en_US')[source]

Return a date formatted according to the given pattern.

>>> dt = datetime(2007, 04, 01, 15, 30)
>>> format_datetime(dt, locale='en_US')
u'Apr 1, 2007, 3:30:00 PM'

For any pattern requiring the display of the time-zone, the third-party pytz package is needed to explicitly specify the time-zone:

>>> format_datetime(dt, 'full', tzinfo=get_timezone('Europe/Paris'),
...                 locale='fr_FR')
u'dimanche 1 avril 2007 17:30:00 heure avanc\xe9e d\u2019Europe centrale'
>>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
...                 tzinfo=get_timezone('US/Eastern'), locale='en')
u'2007.04.01 AD at 11:30:00 EDT'
Parameters:
  • datetime – the datetime object; if None, the current date and time is used
  • format – one of “full”, “long”, “medium”, or “short”, or a custom date/time pattern
  • tzinfo – the timezone to apply to the time for display
  • locale – a Locale object or a locale identifier
babel.dates.format_time(time=None, format='medium', tzinfo=None, locale='en_US')[source]

Return a time formatted according to the given pattern.

>>> t = time(15, 30)
>>> format_time(t, locale='en_US')
u'3:30:00 PM'
>>> format_time(t, format='short', locale='de_DE')
u'15:30'

If you don’t want to use the locale default formats, you can specify a custom time pattern:

>>> format_time(t, "hh 'o''clock' a", locale='en')
u"03 o'clock PM"

For any pattern requiring the display of the time-zone a timezone has to be specified explicitly:

>>> t = datetime(2007, 4, 1, 15, 30)
>>> tzinfo = get_timezone('Europe/Paris')
>>> t = tzinfo.localize(t)
>>> format_time(t, format='full', tzinfo=tzinfo, locale='fr_FR')
u'15:30:00 heure avanc\xe9e d\u2019Europe centrale'
>>> format_time(t, "hh 'o''clock' a, zzzz", tzinfo=get_timezone('US/Eastern'),
...             locale='en')
u"09 o'clock AM, Eastern Daylight Time"

As that example shows, when this function gets passed a datetime.datetime value, the actual time in the formatted string is adjusted to the timezone specified by the tzinfo parameter. If the datetime is “naive” (i.e. it has no associated timezone information), it is assumed to be in UTC.

These timezone calculations are not performed if the value is of type datetime.time, as without date information there’s no way to determine what a given time would translate to in a different timezone without information about whether daylight savings time is in effect or not. This means that time values are left as-is, and the value of the tzinfo parameter is only used to display the timezone name if needed:

>>> t = time(15, 30)
>>> format_time(t, format='full', tzinfo=get_timezone('Europe/Paris'),
...             locale='fr_FR')
u'15:30:00 heure normale de l\u2019Europe centrale'
>>> format_time(t, format='full', tzinfo=get_timezone('US/Eastern'),
...             locale='en_US')
u'3:30:00 PM Eastern Standard Time'
Parameters:
  • time – the time or datetime object; if None, the current time in UTC is used
  • format – one of “full”, “long”, “medium”, or “short”, or a custom date/time pattern
  • tzinfo – the time-zone to apply to the time for display
  • locale – a Locale object or a locale identifier
babel.dates.format_timedelta(delta, granularity='second', threshold=0.85, add_direction=False, format='medium', locale='en_US')[source]

Return a time delta according to the rules of the given locale.

>>> format_timedelta(timedelta(weeks=12), locale='en_US')
u'3 months'
>>> format_timedelta(timedelta(seconds=1), locale='es')
u'1 segundo'

The granularity parameter can be provided to alter the lowest unit presented, which defaults to a second.

>>> format_timedelta(timedelta(hours=3), granularity='day',
...                  locale='en_US')
u'1 day'

The threshold parameter can be used to determine at which value the presentation switches to the next higher unit. A higher threshold factor means the presentation will switch later. For example:

>>> format_timedelta(timedelta(hours=23), threshold=0.9, locale='en_US')
u'1 day'
>>> format_timedelta(timedelta(hours=23), threshold=1.1, locale='en_US')
u'23 hours'

In addition directional information can be provided that informs the user if the date is in the past or in the future:

>>> format_timedelta(timedelta(hours=1), add_direction=True, locale='en')
u'In 1 hour'
>>> format_timedelta(timedelta(hours=-1), add_direction=True, locale='en')
u'1 hour ago'
Parameters:
  • delta – a timedelta object representing the time difference to format, or the delta in seconds as an int value
  • granularity – determines the smallest unit that should be displayed, the value can be one of “year”, “month”, “week”, “day”, “hour”, “minute” or “second”
  • threshold – factor that determines at which point the presentation switches to the next higher unit
  • add_direction – if this flag is set to True the return value will include directional information. For instance a positive timedelta will include the information about it being in the future, a negative will be information about the value being in the past.
  • format – the format (currently only “medium” and “short” are supported)
  • locale – a Locale object or a locale identifier
babel.dates.get_date_format(format='medium', locale='en_US')[source]

Return the date formatting patterns used by the locale for the specified format.

>>> get_date_format(locale='en_US')
<DateTimePattern u'MMM d, y'>
>>> get_date_format('full', locale='de_DE')
<DateTimePattern u'EEEE, d. MMMM y'>
Parameters:
  • format – the format to use, one of “full”, “long”, “medium”, or “short”
  • locale – the Locale object, or a locale string
babel.dates.get_datetime_format(format='medium', locale='en_US')[source]

Return the datetime formatting patterns used by the locale for the specified format.

>>> get_datetime_format(locale='en_US')
u'{1}, {0}'
Parameters:
  • format – the format to use, one of “full”, “long”, “medium”, or “short”
  • locale – the Locale object, or a locale string
babel.dates.get_day_names(width='wide', context='format', locale='en_US')[source]

Return the day names used by the locale for the specified format.

>>> get_day_names('wide', locale='en_US')[1]
u'Tuesday'
>>> get_day_names('abbreviated', locale='es')[1]
u'mar'
>>> get_day_names('narrow', context='stand-alone', locale='de_DE')[1]
u'D'
Parameters:
  • width – the width to use, one of “wide”, “abbreviated”, or “narrow”
  • context – the context, either “format” or “stand-alone”
  • locale – the Locale object, or a locale string
babel.dates.get_era_names(width='wide', locale='en_US')[source]

Return the era names used by the locale for the specified format.

>>> get_era_names('wide', locale='en_US')[1]
u'Anno Domini'
>>> get_era_names('abbreviated', locale='de_DE')[1]
u'n. Chr.'
Parameters:
  • width – the width to use, either “wide”, “abbreviated”, or “narrow”
  • locale – the Locale object, or a locale string
babel.dates.get_month_names(width='wide', context='format', locale='en_US')[source]

Return the month names used by the locale for the specified format.

>>> get_month_names('wide', locale='en_US')[1]
u'January'
>>> get_month_names('abbreviated', locale='es')[1]
u'ene'
>>> get_month_names('narrow', context='stand-alone', locale='de_DE')[1]
u'J'
Parameters:
  • width – the width to use, one of “wide”, “abbreviated”, or “narrow”
  • context – the context, either “format” or “stand-alone”
  • locale – the Locale object, or a locale string
babel.dates.get_next_timezone_transition(zone=None, dt=None)[source]

Given a timezone it will return a TimezoneTransition object that holds the information about the next timezone transition that’s going to happen. For instance this can be used to detect when the next DST change is going to happen and how it looks like.

The transition is calculated relative to the given datetime object. The next transition that follows the date is used. If a transition cannot be found the return value will be None.

Transition information can only be provided for timezones returned by the get_timezone() function.

Parameters:
  • zone – the timezone for which the transition should be looked up. If not provided the local timezone is used.
  • dt – the date after which the next transition should be found. If not given the current time is assumed.
babel.dates.get_period_names(locale='en_US')[source]

Return the names for day periods (AM/PM) used by the locale.

>>> get_period_names(locale='en_US')['am']
u'AM'
Parameters:locale – the Locale object, or a locale string
babel.dates.get_quarter_names(width='wide', context='format', locale='en_US')[source]

Return the quarter names used by the locale for the specified format.

>>> get_quarter_names('wide', locale='en_US')[1]
u'1st quarter'
>>> get_quarter_names('abbreviated', locale='de_DE')[1]
u'Q1'
Parameters:
  • width – the width to use, one of “wide”, “abbreviated”, or “narrow”
  • context – the context, either “format” or “stand-alone”
  • locale – the Locale object, or a locale string
babel.dates.get_time_format(format='medium', locale='en_US')[source]

Return the time formatting patterns used by the locale for the specified format.

>>> get_time_format(locale='en_US')
<DateTimePattern u'h:mm:ss a'>
>>> get_time_format('full', locale='de_DE')
<DateTimePattern u'HH:mm:ss zzzz'>
Parameters:
  • format – the format to use, one of “full”, “long”, “medium”, or “short”
  • locale – the Locale object, or a locale string
babel.dates.get_timezone(zone=None)[source]

Looks up a timezone by name and returns it. The timezone object returned comes from pytz and corresponds to the tzinfo interface and can be used with all of the functions of Babel that operate with dates.

If a timezone is not known a LookupError is raised. If zone is None a local zone object is returned.

Parameters:zone – the name of the timezone to look up. If a timezone object itself is passed in, mit’s returned unchanged.
babel.dates.get_timezone_gmt(datetime=None, width='long', locale='en_US')[source]

Return the timezone associated with the given datetime object formatted as string indicating the offset from GMT.

>>> dt = datetime(2007, 4, 1, 15, 30)
>>> get_timezone_gmt(dt, locale='en')
u'GMT+00:00'
>>> tz = get_timezone('America/Los_Angeles')
>>> dt = tz.localize(datetime(2007, 4, 1, 15, 30))
>>> get_timezone_gmt(dt, locale='en')
u'GMT-07:00'
>>> get_timezone_gmt(dt, 'short', locale='en')
u'-0700'

The long format depends on the locale, for example in France the acronym UTC string is used instead of GMT:

>>> get_timezone_gmt(dt, 'long', locale='fr_FR')
u'UTC-07:00'

New in version 0.9.

Parameters:
  • datetime – the datetime object; if None, the current date and time in UTC is used
  • width – either “long” or “short”
  • locale – the Locale object, or a locale string
babel.dates.get_timezone_location(dt_or_tzinfo=None, locale='en_US')[source]

Return a representation of the given timezone using “location format”.

The result depends on both the local display name of the country and the city associated with the time zone:

>>> tz = get_timezone('America/St_Johns')
>>> get_timezone_location(tz, locale='de_DE')
u"Kanada (St. John's) Zeit"
>>> tz = get_timezone('America/Mexico_City')
>>> get_timezone_location(tz, locale='de_DE')
u'Mexiko (Mexiko-Stadt) Zeit'

If the timezone is associated with a country that uses only a single timezone, just the localized country name is returned:

>>> tz = get_timezone('Europe/Berlin')
>>> get_timezone_name(tz, locale='de_DE')
u'Mitteleurop\xe4ische Zeit'

New in version 0.9.

Parameters:
  • dt_or_tzinfo – the datetime or tzinfo object that determines the timezone; if None, the current date and time in UTC is assumed
  • locale – the Locale object, or a locale string
Returns:

the localized timezone name using location format

babel.dates.get_timezone_name(dt_or_tzinfo=None, width='long', uncommon=False, locale='en_US', zone_variant=None)[source]

Return the localized display name for the given timezone. The timezone may be specified using a datetime or tzinfo object.

>>> dt = time(15, 30, tzinfo=get_timezone('America/Los_Angeles'))
>>> get_timezone_name(dt, locale='en_US')
u'Pacific Standard Time'
>>> get_timezone_name(dt, width='short', locale='en_US')
u'PST'

If this function gets passed only a tzinfo object and no concrete datetime, the returned display name is indenpendent of daylight savings time. This can be used for example for selecting timezones, or to set the time of events that recur across DST changes:

>>> tz = get_timezone('America/Los_Angeles')
>>> get_timezone_name(tz, locale='en_US')
u'Pacific Time'
>>> get_timezone_name(tz, 'short', locale='en_US')
u'PT'

If no localized display name for the timezone is available, and the timezone is associated with a country that uses only a single timezone, the name of that country is returned, formatted according to the locale:

>>> tz = get_timezone('Europe/Berlin')
>>> get_timezone_name(tz, locale='de_DE')
u'Mitteleurop\xe4ische Zeit'
>>> get_timezone_name(tz, locale='pt_BR')
u'Hor\xe1rio da Europa Central'

On the other hand, if the country uses multiple timezones, the city is also included in the representation:

>>> tz = get_timezone('America/St_Johns')
>>> get_timezone_name(tz, locale='de_DE')
u'Neufundland-Zeit'

Note that short format is currently not supported for all timezones and all locales. This is partially because not every timezone has a short code in every locale. In that case it currently falls back to the long format.

For more information see LDML Appendix J: Time Zone Display Names

New in version 0.9.

Changed in version 1.0: Added zone_variant support.

Parameters:
  • dt_or_tzinfo – the datetime or tzinfo object that determines the timezone; if a tzinfo object is used, the resulting display name will be generic, i.e. independent of daylight savings time; if None, the current date in UTC is assumed
  • width – either “long” or “short”
  • uncommon – deprecated and ignored
  • zone_variant – defines the zone variation to return. By default the variation is defined from the datetime object passed in. If no datetime object is passed in, the 'generic' variation is assumed. The following values are valid: 'generic', 'daylight' and 'standard'.
  • locale – the Locale object, or a locale string
babel.dates.parse_date(string, locale='en_US')[source]

Parse a date from a string.

This function uses the date format for the locale as a hint to determine the order in which the date fields appear in the string.

>>> parse_date('4/1/04', locale='en_US')
datetime.date(2004, 4, 1)
>>> parse_date('01.04.2004', locale='de_DE')
datetime.date(2004, 4, 1)
Parameters:
  • string – the string containing the date
  • locale – a Locale object or a locale identifier
babel.dates.parse_pattern(pattern)[source]

Parse date, time, and datetime format patterns.

>>> parse_pattern("MMMMd").format
u'%(MMMM)s%(d)s'
>>> parse_pattern("MMM d, yyyy").format
u'%(MMM)s %(d)s, %(yyyy)s'

Pattern can contain literal strings in single quotes:

>>> parse_pattern("H:mm' Uhr 'z").format
u'%(H)s:%(mm)s Uhr %(z)s'

An actual single quote can be used by using two adjacent single quote characters:

>>> parse_pattern("hh' o''clock'").format
u"%(hh)s o'clock"
Parameters:pattern – the formatting pattern to parse
babel.dates.parse_time(string, locale='en_US')[source]

Parse a time from a string.

This function uses the time format for the locale as a hint to determine the order in which the time fields appear in the string.

>>> parse_time('15:30:00', locale='en_US')
datetime.time(15, 30)
Parameters:
  • string – the string containing the time
  • locale – a Locale object or a locale identifier
Returns:

the parsed time

Return type:

time

babel.numbers module

babel.numbers

Locale dependent formatting and parsing of numeric data.

The default locale for the functions in this module is determined by the following environment variables, in that order:

  • LC_NUMERIC,
  • LC_ALL, and
  • LANG
copyright:
  1. 2013 by the Babel Team.
license:

BSD, see LICENSE for more details.

exception babel.numbers.NumberFormatError[source]

Bases: exceptions.ValueError

Exception raised when a string cannot be parsed into a number.

class babel.numbers.NumberPattern(pattern, prefix, suffix, grouping, int_prec, frac_prec, exp_prec, exp_plus)[source]

Bases: object

apply(value, locale, currency=None)[source]
babel.numbers.bankersround(value, ndigits=0)[source]

Round a number to a given precision.

Works like round() except that the round-half-even (banker’s rounding) algorithm is used instead of round-half-up.

>>> bankersround(5.5, 0)
6.0
>>> bankersround(6.5, 0)
6.0
>>> bankersround(-6.5, 0)
-6.0
>>> bankersround(1234.0, -2)
1200.0
babel.numbers.format_currency(number, currency, format=None, locale='en_US')[source]

Return formatted currency value.

>>> format_currency(1099.98, 'USD', locale='en_US')
u'$1,099.98'
>>> format_currency(1099.98, 'USD', locale='es_CO')
u'1.099,98\xa0US$'
>>> format_currency(1099.98, 'EUR', locale='de_DE')
u'1.099,98\xa0\u20ac'

The pattern can also be specified explicitly. The currency is placed with the ‘¤’ sign. As the sign gets repeated the format expands (¤ being the symbol, ¤¤ is the currency abbreviation and ¤¤¤ is the full name of the currency):

>>> format_currency(1099.98, 'EUR', u'¤¤ #,##0.00', locale='en_US')
u'EUR 1,099.98'
>>> format_currency(1099.98, 'EUR', u'#,##0.00 ¤¤¤', locale='en_US')
u'1,099.98 euros'
Parameters:
  • number – the number to format
  • currency – the currency code
  • locale – the Locale object or locale identifier
babel.numbers.format_decimal(number, format=None, locale='en_US')[source]

Return the given decimal number formatted for a specific locale.

>>> format_decimal(1.2345, locale='en_US')
u'1.234'
>>> format_decimal(1.2346, locale='en_US')
u'1.235'
>>> format_decimal(-1.2346, locale='en_US')
u'-1.235'
>>> format_decimal(1.2345, locale='sv_SE')
u'1,234'
>>> format_decimal(1.2345, locale='de')
u'1,234'

The appropriate thousands grouping and the decimal separator are used for each locale:

>>> format_decimal(12345.5, locale='en_US')
u'12,345.5'
Parameters:
  • number – the number to format
  • format
  • locale – the Locale object or locale identifier
babel.numbers.format_number(number, locale='en_US')[source]

Return the given number formatted for a specific locale.

>>> format_number(1099, locale='en_US')
u'1,099'
>>> format_number(1099, locale='de_DE')
u'1.099'
Parameters:
  • number – the number to format
  • locale – the Locale object or locale identifier
babel.numbers.format_percent(number, format=None, locale='en_US')[source]

Return formatted percent value for a specific locale.

>>> format_percent(0.34, locale='en_US')
u'34%'
>>> format_percent(25.1234, locale='en_US')
u'2,512%'
>>> format_percent(25.1234, locale='sv_SE')
u'2\xa0512\xa0%'

The format pattern can also be specified explicitly:

>>> format_percent(25.1234, u'#,##0\u2030', locale='en_US')
u'25,123\u2030'
Parameters:
  • number – the percent number to format
  • format
  • locale – the Locale object or locale identifier
babel.numbers.format_scientific(number, format=None, locale='en_US')[source]

Return value formatted in scientific notation for a specific locale.

>>> format_scientific(10000, locale='en_US')
u'1E4'

The format pattern can also be specified explicitly:

>>> format_scientific(1234567, u'##0E00', locale='en_US')
u'1.23E06'
Parameters:
  • number – the number to format
  • format
  • locale – the Locale object or locale identifier
babel.numbers.get_currency_name(currency, count=None, locale='en_US')[source]

Return the name used by the locale for the specified currency.

>>> get_currency_name('USD', locale='en_US')
u'US Dollar'

New in version 0.9.4.

Parameters:
  • currency – the currency code
  • count – the optional count. If provided the currency name will be pluralized to that number if possible.
  • locale – the Locale object or locale identifier
babel.numbers.get_currency_symbol(currency, locale='en_US')[source]

Return the symbol used by the locale for the specified currency.

>>> get_currency_symbol('USD', locale='en_US')
u'$'
Parameters:
  • currency – the currency code
  • locale – the Locale object or locale identifier
babel.numbers.get_decimal_symbol(locale='en_US')[source]

Return the symbol used by the locale to separate decimal fractions.

>>> get_decimal_symbol('en_US')
u'.'
Parameters:locale – the Locale object or locale identifier
babel.numbers.get_exponential_symbol(locale='en_US')[source]

Return the symbol used by the locale to separate mantissa and exponent.

>>> get_exponential_symbol('en_US')
u'E'
Parameters:locale – the Locale object or locale identifier
babel.numbers.get_group_symbol(locale='en_US')[source]

Return the symbol used by the locale to separate groups of thousands.

>>> get_group_symbol('en_US')
u','
Parameters:locale – the Locale object or locale identifier
babel.numbers.get_minus_sign_symbol(locale='en_US')[source]

Return the plus sign symbol used by the current locale.

>>> get_minus_sign_symbol('en_US')
u'-'
Parameters:locale – the Locale object or locale identifier
babel.numbers.get_plus_sign_symbol(locale='en_US')[source]

Return the plus sign symbol used by the current locale.

>>> get_plus_sign_symbol('en_US')
u'+'
Parameters:locale – the Locale object or locale identifier
babel.numbers.get_territory_currencies(territory, start_date=None, end_date=None, tender=True, non_tender=False, include_details=False)[source]

Returns the list of currencies for the given territory that are valid for the given date range. In addition to that the currency database distinguishes between tender and non-tender currencies. By default only tender currencies are returned.

The return value is a list of all currencies roughly ordered by the time of when the currency became active. The longer the currency is being in use the more to the left of the list it will be.

The start date defaults to today. If no end date is given it will be the same as the start date. Otherwise a range can be defined. For instance this can be used to find the currencies in use in Austria between 1995 and 2011:

>>> from datetime import date
>>> get_territory_currencies('AT', date(1995, 1, 1), date(2011, 1, 1))
['ATS', 'EUR']

Likewise it’s also possible to find all the currencies in use on a single date:

>>> get_territory_currencies('AT', date(1995, 1, 1))
['ATS']
>>> get_territory_currencies('AT', date(2011, 1, 1))
['EUR']

By default the return value only includes tender currencies. This however can be changed:

>>> get_territory_currencies('US')
['USD']
>>> get_territory_currencies('US', tender=False, non_tender=True)
['USN', 'USS']

New in version 2.0.

Parameters:
  • territory – the name of the territory to find the currency fo
  • start_date – the start date. If not given today is assumed.
  • end_date – the end date. If not given the start date is assumed.
  • tender – controls whether tender currencies should be included.
  • non_tender – controls whether non-tender currencies should be included.
  • include_details – if set to True, instead of returning currency codes the return value will be dictionaries with detail information. In that case each dictionary will have the keys 'currency', 'from', 'to', and 'tender'.
babel.numbers.parse_decimal(string, locale='en_US')[source]

Parse localized decimal string into a decimal.

>>> parse_decimal('1,099.98', locale='en_US')
Decimal('1099.98')
>>> parse_decimal('1.099,98', locale='de')
Decimal('1099.98')

When the given string cannot be parsed, an exception is raised:

>>> parse_decimal('2,109,998', locale='de')
Traceback (most recent call last):
    ...
NumberFormatError: '2,109,998' is not a valid decimal number
Parameters:
  • string – the string to parse
  • locale – the Locale object or locale identifier
Raises NumberFormatError:
 

if the string can not be converted to a decimal number

babel.numbers.parse_grouping(p)[source]

Parse primary and secondary digit grouping

>>> parse_grouping('##')
(1000, 1000)
>>> parse_grouping('#,###')
(3, 3)
>>> parse_grouping('#,####,###')
(3, 4)
babel.numbers.parse_number(string, locale='en_US')[source]

Parse localized number string into an integer.

>>> parse_number('1,099', locale='en_US')
1099
>>> parse_number('1.099', locale='de_DE')
1099

When the given string cannot be parsed, an exception is raised:

>>> parse_number('1.099,98', locale='de')
Traceback (most recent call last):
    ...
NumberFormatError: '1.099,98' is not a valid number
Parameters:
  • string – the string to parse
  • locale – the Locale object or locale identifier
Returns:

the parsed number

Raises NumberFormatError:
 

if the string can not be converted to a number

babel.numbers.parse_pattern(pattern)[source]

Parse number format patterns

babel.numbers.split_number(value)[source]

Convert a number into a (intasstring, fractionasstring) tuple

babel.plural module

babel.numbers

CLDR Plural support. See UTS #35.

copyright:
  1. 2013 by the Babel Team.
license:

BSD, see LICENSE for more details.

class babel.plural.PluralRule(rules)[source]

Bases: object

Represents a set of language pluralization rules. The constructor accepts a list of (tag, expr) tuples or a dict of CLDR rules. The resulting object is callable and accepts one parameter with a positive or negative number (both integer and float) for the number that indicates the plural form for a string and returns the tag for the format:

>>> rule = PluralRule({'one': 'n is 1'})
>>> rule(1)
'one'
>>> rule(2)
'other'

Currently the CLDR defines these tags: zero, one, two, few, many and other where other is an implicit default. Rules should be mutually exclusive; for a given numeric value, only one rule should apply (i.e. the condition should only be true for one of the plural rule elements.

abstract
classmethod parse(rules)[source]

Create a PluralRule instance for the given rules. If the rules are a PluralRule object, that object is returned.

Parameters:rules – the rules as list or dict, or a PluralRule object
Raises RuleError:
 if the expression is malformed
rules

The PluralRule as a dict of unicode plural rules.

>>> rule = PluralRule({'one': 'n is 1'})
>>> rule.rules
{'one': 'n is 1'}
tags

A set of explicitly defined tags in this rule. The implicit default 'other' rules is not part of this set unless there is an explicit rule for it.

exception babel.plural.RuleError[source]

Bases: exceptions.Exception

Raised if a rule is malformed.

babel.plural.cldr_modulo(a, b)[source]

Javaish modulo. This modulo operator returns the value with the sign of the dividend rather than the divisor like Python does:

>>> cldr_modulo(-3, 5)
-3
>>> cldr_modulo(-3, -5)
-3
>>> cldr_modulo(3, 5)
3
babel.plural.in_range_list(num, range_list)[source]

Integer range list test. This is the callback for the “in” operator of the UTS #35 pluralization rule language:

>>> in_range_list(1, [(1, 3)])
True
>>> in_range_list(3, [(1, 3)])
True
>>> in_range_list(3, [(1, 3), (5, 8)])
True
>>> in_range_list(1.2, [(1, 4)])
False
>>> in_range_list(10, [(1, 4)])
False
>>> in_range_list(10, [(1, 4), (6, 8)])
False
babel.plural.to_gettext(rule)[source]

The plural rule as gettext expression. The gettext expression is technically limited to integers and returns indices rather than tags.

>>> to_gettext({'one': 'n is 1', 'two': 'n is 2'})
'nplurals=3; plural=((n == 1) ? 0 : (n == 2) ? 1 : 2)'
Parameters:rule – the rules as list or dict, or a PluralRule object
Raises RuleError:
 if the expression is malformed
babel.plural.to_javascript(rule)[source]

Convert a list/dict of rules or a PluralRule object into a JavaScript function. This function depends on no external library:

>>> to_javascript({'one': 'n is 1'})
"(function(n) { return (n == 1) ? 'one' : 'other'; })"

Implementation detail: The function generated will probably evaluate expressions involved into range operations multiple times. This has the advantage that external helper functions are not required and is not a big performance hit for these simple calculations.

Parameters:rule – the rules as list or dict, or a PluralRule object
Raises RuleError:
 if the expression is malformed
babel.plural.to_python(rule)[source]

Convert a list/dict of rules or a PluralRule object into a regular Python function. This is useful in situations where you need a real function and don’t are about the actual rule object:

>>> func = to_python({'one': 'n is 1', 'few': 'n in 2..4'})
>>> func(1)
'one'
>>> func(3)
'few'
>>> func = to_python({'one': 'n in 1,11', 'few': 'n in 3..10,13..19'})
>>> func(11)
'one'
>>> func(15)
'few'
Parameters:rule – the rules as list or dict, or a PluralRule object
Raises RuleError:
 if the expression is malformed
babel.plural.within_range_list(num, range_list)[source]

Float range test. This is the callback for the “within” operator of the UTS #35 pluralization rule language:

>>> within_range_list(1, [(1, 3)])
True
>>> within_range_list(1.0, [(1, 3)])
True
>>> within_range_list(1.2, [(1, 4)])
True
>>> within_range_list(8.8, [(1, 4), (7, 15)])
True
>>> within_range_list(10, [(1, 4)])
False
>>> within_range_list(10.5, [(1, 4), (20, 30)])
False

babel.support module

babel.support

Several classes and functions that help with integrating and using Babel in applications.

copyright:
  1. 2013 by the Babel Team.
license:

BSD, see LICENSE for more details.

class babel.support.Format(locale, tzinfo=None)[source]

Bases: object

Wrapper class providing the various date and number formatting functions bound to a specific locale and time-zone.

>>> from babel.util import UTC
>>> from datetime import date
>>> fmt = Format('en_US', UTC)
>>> fmt.date(date(2007, 4, 1))
u'Apr 1, 2007'
>>> fmt.decimal(1.2345)
u'1.234'
currency(number, currency)[source]

Return a number in the given currency formatted for the locale.

date(date=None, format='medium')[source]

Return a date formatted according to the given pattern.

>>> from datetime import date
>>> fmt = Format('en_US')
>>> fmt.date(date(2007, 4, 1))
u'Apr 1, 2007'
datetime(datetime=None, format='medium')[source]

Return a date and time formatted according to the given pattern.

>>> from datetime import datetime
>>> from pytz import timezone
>>> fmt = Format('en_US', tzinfo=timezone('US/Eastern'))
>>> fmt.datetime(datetime(2007, 4, 1, 15, 30))
u'Apr 1, 2007, 11:30:00 AM'
decimal(number, format=None)[source]

Return a decimal number formatted for the locale.

>>> fmt = Format('en_US')
>>> fmt.decimal(1.2345)
u'1.234'
number(number)[source]

Return an integer number formatted for the locale.

>>> fmt = Format('en_US')
>>> fmt.number(1099)
u'1,099'
percent(number, format=None)[source]

Return a number formatted as percentage for the locale.

>>> fmt = Format('en_US')
>>> fmt.percent(0.34)
u'34%'
scientific(number)[source]

Return a number formatted using scientific notation for the locale.

time(time=None, format='medium')[source]

Return a time formatted according to the given pattern.

>>> from datetime import datetime
>>> from pytz import timezone
>>> fmt = Format('en_US', tzinfo=timezone('US/Eastern'))
>>> fmt.time(datetime(2007, 4, 1, 15, 30))
u'11:30:00 AM'
timedelta(delta, granularity='second', threshold=0.85, format='medium', add_direction=False)[source]

Return a time delta according to the rules of the given locale.

>>> from datetime import timedelta
>>> fmt = Format('en_US')
>>> fmt.timedelta(timedelta(weeks=11))
u'3 months'
class babel.support.LazyProxy(func, *args, **kwargs)[source]

Bases: object

Class for proxy objects that delegate to a specified function to evaluate the actual object.

>>> def greeting(name='world'):
...     return 'Hello, %s!' % name
>>> lazy_greeting = LazyProxy(greeting, name='Joe')
>>> print lazy_greeting
Hello, Joe!
>>> u'  ' + lazy_greeting
u'  Hello, Joe!'
>>> u'(%s)' % lazy_greeting
u'(Hello, Joe!)'

This can be used, for example, to implement lazy translation functions that delay the actual translation until the string is actually used. The rationale for such behavior is that the locale of the user may not always be available. In web applications, you only know the locale when processing a request.

The proxy implementation attempts to be as complete as possible, so that the lazy objects should mostly work as expected, for example for sorting:

>>> greetings = [
...     LazyProxy(greeting, 'world'),
...     LazyProxy(greeting, 'Joe'),
...     LazyProxy(greeting, 'universe'),
... ]
>>> greetings.sort()
>>> for greeting in greetings:
...     print greeting
Hello, Joe!
Hello, universe!
Hello, world!
value
class babel.support.NullTranslations(fp=None)[source]

Bases: gettext.NullTranslations, object

CONTEXT_ENCODING = '%s\x04%s'
DEFAULT_DOMAIN = None
dgettext(domain, message)[source]

Like gettext(), but look the message up in the specified domain.

dngettext(domain, singular, plural, num)[source]

Like ngettext(), but look the message up in the specified domain.

dnpgettext(domain, context, singular, plural, num)[source]

Like npgettext, but look the message up in the specified domain.

dpgettext(domain, context, message)[source]

Like pgettext(), but look the message up in the specified domain.

dugettext(domain, message)

Like ugettext(), but look the message up in the specified domain.

dungettext(domain, singular, plural, num)

Like ungettext() but look the message up in the specified domain.

dunpgettext(domain, context, singular, plural, num)

Like unpgettext, but look the message up in the specified domain.

dupgettext(domain, context, message)

Like upgettext(), but look the message up in the specified domain.

ldgettext(domain, message)[source]

Like lgettext(), but look the message up in the specified domain.

ldngettext(domain, singular, plural, num)[source]

Like lngettext(), but look the message up in the specified domain.

ldnpgettext(domain, context, singular, plural, num)[source]

Equivalent to dnpgettext(), but the translation is returned in the preferred system encoding, if no other encoding was explicitly set with bind_textdomain_codeset().

ldpgettext(domain, context, message)[source]

Equivalent to dpgettext(), but the translation is returned in the preferred system encoding, if no other encoding was explicitly set with bind_textdomain_codeset().

lnpgettext(context, singular, plural, num)[source]

Equivalent to npgettext(), but the translation is returned in the preferred system encoding, if no other encoding was explicitly set with bind_textdomain_codeset().

lpgettext(context, message)[source]

Equivalent to pgettext(), but the translation is returned in the preferred system encoding, if no other encoding was explicitly set with bind_textdomain_codeset().

npgettext(context, singular, plural, num)[source]

Do a plural-forms lookup of a message id. singular is used as the message id for purposes of lookup in the catalog, while num is used to determine which plural form to use. The returned message string is an 8-bit string encoded with the catalog’s charset encoding, if known.

If the message id for context is not found in the catalog, and a fallback is specified, the request is forwarded to the fallback’s npgettext() method. Otherwise, when num is 1 singular is returned, and plural is returned in all other cases.

pgettext(context, message)[source]

Look up the context and message id in the catalog and return the corresponding message string, as an 8-bit string encoded with the catalog’s charset encoding, if known. If there is no entry in the catalog for the message id and context , and a fallback has been set, the look up is forwarded to the fallback’s pgettext() method. Otherwise, the message id is returned.

udgettext(domain, message)[source]

Like ugettext(), but look the message up in the specified domain.

udngettext(domain, singular, plural, num)[source]

Like ungettext() but look the message up in the specified domain.

udnpgettext(domain, context, singular, plural, num)[source]

Like unpgettext, but look the message up in the specified domain.

udpgettext(domain, context, message)[source]

Like upgettext(), but look the message up in the specified domain.

unpgettext(context, singular, plural, num)[source]

Do a plural-forms lookup of a message id. singular is used as the message id for purposes of lookup in the catalog, while num is used to determine which plural form to use. The returned message string is a Unicode string.

If the message id for context is not found in the catalog, and a fallback is specified, the request is forwarded to the fallback’s unpgettext() method. Otherwise, when num is 1 singular is returned, and plural is returned in all other cases.

upgettext(context, message)[source]

Look up the context and message id in the catalog and return the corresponding message string, as a Unicode string. If there is no entry in the catalog for the message id and context, and a fallback has been set, the look up is forwarded to the fallback’s upgettext() method. Otherwise, the message id is returned.

class babel.support.Translations(fp=None, domain=None)[source]

Bases: babel.support.NullTranslations, gettext.GNUTranslations

An extended translation catalog class.

DEFAULT_DOMAIN = 'messages'
add(translations, merge=True)[source]

Add the given translations to the catalog.

If the domain of the translations is different than that of the current catalog, they are added as a catalog that is only accessible by the various d*gettext functions.

Parameters:
  • translations – the Translations instance with the messages to add
  • merge – whether translations for message domains that have already been added should be merged with the existing translations
classmethod load(dirname=None, locales=None, domain=None)[source]

Load translations from the given directory.

Parameters:
  • dirname – the directory containing the MO files
  • locales – the list of locales in order of preference (items in this list can be either Locale objects or locale strings)
  • domain – the message domain (default: ‘messages’)
merge(translations)[source]

Merge the given translations into the catalog.

Message translations in the specified catalog override any messages with the same identifier in the existing catalog.

Parameters:translations – the Translations instance with the messages to merge

babel.util module

babel.util

Various utility classes and functions.

copyright:
  1. 2013 by the Babel Team.
license:

BSD, see LICENSE for more details.

class babel.util.FixedOffsetTimezone(offset, name=None)[source]

Bases: datetime.tzinfo

Fixed offset in minutes east from UTC.

dst(dt)[source]
tzname(dt)[source]
utcoffset(dt)[source]
class babel.util.TextWrapper(width=70, initial_indent='', subsequent_indent='', expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True)[source]

Bases: textwrap.TextWrapper

wordsep_re = <_sre.SRE_Pattern object>
babel.util.distinct(iterable)[source]

Yield all items in an iterable collection that are distinct.

Unlike when using sets for a similar effect, the original ordering of the items in the collection is preserved by this function.

>>> print list(distinct([1, 2, 1, 3, 4, 4]))
[1, 2, 3, 4]
>>> print list(distinct('foobar'))
['f', 'o', 'b', 'a', 'r']
Parameters:iterable – the iterable collection providing the data
class babel.util.odict(data=None)[source]

Bases: dict

Ordered dict implementation.

See:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747
clear()[source]
copy()[source]
items()[source]
iteritems()[source]
iterkeys()
itervalues()[source]
keys()[source]
pop(key, default=<object object>)[source]
popitem(key)[source]
setdefault(key, failobj=None)[source]
update(dict)[source]
values()[source]
babel.util.parse_encoding(fp)[source]

Deduce the encoding of a source file from magic comment.

It does this in the same way as the Python interpreter

The fp argument should be a seekable file object.

(From Jeff Dairiki)

babel.util.pathmatch(pattern, filename)[source]

Extended pathname pattern matching.

This function is similar to what is provided by the fnmatch module in the Python standard library, but:

  • can match complete (relative or absolute) path names, and not just file names, and
  • also supports a convenience pattern (“**”) to match files at any directory level.

Examples:

>>> pathmatch('**.py', 'bar.py')
True
>>> pathmatch('**.py', 'foo/bar/baz.py')
True
>>> pathmatch('**.py', 'templates/index.html')
False
>>> pathmatch('**/templates/*.html', 'templates/index.html')
True
>>> pathmatch('**/templates/*.html', 'templates/foo/bar.html')
False
Parameters:
  • pattern – the glob pattern
  • filename – the path name of the file to match against
babel.util.wraptext(text, width=70, initial_indent='', subsequent_indent='')[source]

Simple wrapper around the textwrap.wrap function in the standard library. This version does not wrap lines on hyphens in words.

Parameters:
  • text – the text to wrap
  • width – the maximum line width
  • initial_indent – string that will be prepended to the first line of wrapped output
  • subsequent_indent – string that will be prepended to all lines save the first of wrapped output

Module contents

babel

Integrated collection of utilities that assist in internationalizing and localizing applications.

This package is basically composed of two major parts:

  • tools to build and work with gettext message catalogs
  • a Python interface to the CLDR (Common Locale Data Repository), providing access to various locale display names, localized number and date formatting, etc.
copyright:
  1. 2013 by the Babel Team.
license:

BSD, see LICENSE for more details.