本文整理汇总了Python中babel.core.get_global函数的典型用法代码示例。如果您正苦于以下问题:Python get_global函数的具体用法?Python get_global怎么用?Python get_global使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_global函数的19个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: match_language
def match_language(locale_code, lang_list=[], custom_aliases={}, fallback='en-US'):
# try to get language from given locale_code
language = _match_language(locale_code, lang_list, custom_aliases)
if language:
return language
locale_parts = locale_code.split('-')
lang_code = locale_parts[0]
# try to get language using an equivalent country code
if len(locale_parts) > 1:
country_alias = get_global('territory_aliases').get(locale_parts[-1])
if country_alias:
language = _match_language(lang_code + '-' + country_alias[0], lang_list, custom_aliases)
if language:
return language
# try to get language using an equivalent language code
alias = get_global('language_aliases').get(lang_code)
if alias:
language = _match_language(alias, lang_list, custom_aliases)
if language:
return language
if lang_code != locale_code:
# try to get language from given language without giving the country
language = _match_language(lang_code, lang_list, custom_aliases)
return language or fallback
开发者ID:asciimoo,项目名称:searx,代码行数:29,代码来源:utils.py
示例2: _babel_has_locale_data
def _babel_has_locale_data():
from babel import core
try:
core.get_global(None)
return True
except RuntimeError:
return False
开发者ID:akx,项目名称:kompassi,代码行数:8,代码来源:kompassi_i18n.py
示例3: get_currency_fraction
def get_currency_fraction(currency):
fractions = get_global('currency_fractions')
try:
fraction = fractions[currency]
except KeyError:
fraction = fractions['DEFAULT']
return fraction[0]
开发者ID:mirumee,项目名称:django-prices,代码行数:7,代码来源:prices_i18n.py
示例4: get_territory_language_info
def get_territory_language_info(territory):
"""
Get a dictionary of language information for a territory.
The dictionary is keyed by language code; the values are dicts with more information.
The following keys are currently known for the values:
* `population_percent`: The percentage of the territory's population speaking the
language.
* `official_status`: An optional string describing the officiality status of the language.
Known values are "official", "official_regional" and "de_facto_official".
.. warning:: Note that the data is as up to date as the current version of the CLDR used
by Babel. If you need scientifically accurate information, use another source!
.. note:: Note that the format of the dict returned may change between Babel versions.
See http://www.unicode.org/cldr/charts/latest/supplemental/territory_language_information.html
:param territory: Territory code
:type territory: str
:return: Language information dictionary
:rtype: dict[str, dict]
"""
territory = str(territory).upper()
return get_global("territory_languages").get(territory, {}).copy()
开发者ID:AaronJaramillo,项目名称:shopDPM,代码行数:27,代码来源:languages.py
示例5: test_basic
def test_basic(self):
print('RL', get_global('rbnf_locales'))
x = rbnf.RuleBasedNumberFormat.negotiate('hu_HU')
print('L', x._locale)
print('RR', x.available_rulesets)
assert x.format(20) == "húsz"
开发者ID:blagasz,项目名称:babel,代码行数:8,代码来源:test_number_spelling.py
示例6: load
def load(name, merge_inherited=True):
"""Load the locale data for the given locale.
The locale data is a dictionary that contains much of the data defined by
the Common Locale Data Repository (CLDR). This data is stored as a
collection of pickle files inside the ``babel`` package.
>>> d = load('en_US')
>>> d['languages']['sv']
u'Swedish'
Note that the results are cached, and subsequent requests for the same
locale return the same dictionary:
>>> d1 = load('en_US')
>>> d2 = load('en_US')
>>> d1 is d2
True
:param name: the locale identifier string (or "root")
:param merge_inherited: whether the inherited data should be merged into
the data of the requested locale
:raise `IOError`: if no locale data file is found for the given locale
identifer, or one of the locales it inherits from
"""
_cache_lock.acquire()
try:
data = _cache.get(name)
if not data:
# Load inherited data
if name == 'root' or not merge_inherited:
data = {}
else:
from babel.core import get_global
parent = get_global('parent_exceptions').get(name)
if not parent:
parts = name.split('_')
if len(parts) == 1:
parent = 'root'
else:
parent = '_'.join(parts[:-1])
data = load(parent).copy()
filename = os.path.join(_dirname, '%s.dat' % name)
fileobj = open(filename, 'rb')
try:
if name != 'root' and merge_inherited:
merge(data, pickle.load(fileobj))
else:
data = pickle.load(fileobj)
_cache[name] = data
finally:
fileobj.close()
return data
finally:
_cache_lock.release()
开发者ID:marcosptf,项目名称:fedora,代码行数:55,代码来源:localedata.py
示例7: negotiate
def negotiate(cls, locale):
"""
Negotiate proper RBNF rules based on global data
item `rbnf_locales`
Caching is not necessary the Locale object does that pretty well
"""
loc = Locale.negotiate([str(Locale.parse(locale))], get_global('rbnf_locales'))
print('TL', type(loc))
return cls(loc)
开发者ID:blagasz,项目名称:babel,代码行数:12,代码来源:rbnf.py
示例8: get_currency_precision
def get_currency_precision(currency):
"""Return currency's precision.
Precision is the number of decimals found after the decimal point in the
currency's format pattern.
.. versionadded:: 2.5.0
:param currency: the currency code.
"""
precisions = get_global('currency_fractions')
return precisions.get(currency, precisions['DEFAULT'])[0]
开发者ID:python-babel,项目名称:babel,代码行数:12,代码来源:numbers.py
示例9: list_currencies
def list_currencies(locale=None):
""" Return a `set` of normalized currency codes.
.. versionadded:: 2.5.0
:param locale: filters returned currency codes by the provided locale.
Expected to be a locale instance or code. If no locale is
provided, returns the list of all currencies from all
locales.
"""
# Get locale-scoped currencies.
if locale:
currencies = Locale.parse(locale).currencies.keys()
else:
currencies = get_global('all_currencies')
return set(currencies)
开发者ID:python-babel,项目名称:babel,代码行数:16,代码来源:numbers.py
示例10: get_official_languages
def get_official_languages(territory, regional=False, de_facto=False):
"""
Get the official language(s) for the given territory.
The language codes, if any are known, are returned in order of descending popularity.
If the `regional` flag is set, then languages which are regionally official are also returned.
If the `de_facto` flag is set, then languages which are "de facto" official are also returned.
.. warning:: Note that the data is as up to date as the current version of the CLDR used
by Babel. If you need scientifically accurate information, use another source!
:param territory: Territory code
:type territory: str
:param regional: Whether to return regionally official languages too
:type regional: bool
:param de_facto: Whether to return de-facto official languages too
:type de_facto: bool
:return: Tuple of language codes
:rtype: tuple[str]
"""
territory = str(territory).upper()
allowed_stati = set(("official",))
if regional:
allowed_stati.add("official_regional")
if de_facto:
allowed_stati.add("de_facto_official")
languages = get_global("territory_languages").get(territory, {})
pairs = [
(info['population_percent'], language)
for language, info in languages.items()
if info.get('official_status') in allowed_stati
]
pairs.sort(reverse=True)
return tuple(lang for _, lang in pairs)
开发者ID:AaronJaramillo,项目名称:shopDPM,代码行数:38,代码来源:languages.py
示例11: _match_language
def _match_language(lang_code, lang_list=[], custom_aliases={}):
# replace language code with a custom alias if necessary
if lang_code in custom_aliases:
lang_code = custom_aliases[lang_code]
if lang_code in lang_list:
return lang_code
# try to get the most likely country for this language
subtags = get_global('likely_subtags').get(lang_code)
if subtags:
subtag_parts = subtags.split('_')
new_code = subtag_parts[0] + '-' + subtag_parts[-1]
if new_code in custom_aliases:
new_code = custom_aliases[new_code]
if new_code in lang_list:
return new_code
# try to get the any supported country for this language
for lc in lang_list:
if lang_code == lc.split('-')[0]:
return lc
return None
开发者ID:asciimoo,项目名称:searx,代码行数:24,代码来源:utils.py
示例12: get_territory_currencies
def get_territory_currencies(territory, start_date=None, end_date=None,
tender=True, non_tender=False,
include_details=False):
"""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,
... start_date=date(2014, 1, 1))
['USN', 'USS']
.. versionadded:: 2.0
:param territory: the name of the territory to find the currency fo
:param start_date: the start date. If not given today is assumed.
:param end_date: the end date. If not given the start date is assumed.
:param tender: controls whether tender currencies should be included.
:param non_tender: controls whether non-tender currencies should be
included.
:param 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'``.
"""
currencies = get_global('territory_currencies')
if start_date is None:
start_date = date_.today()
elif isinstance(start_date, datetime_):
start_date = start_date.date()
if end_date is None:
end_date = start_date
elif isinstance(end_date, datetime_):
end_date = end_date.date()
curs = currencies.get(territory.upper(), ())
# TODO: validate that the territory exists
def _is_active(start, end):
return (start is None or start <= end_date) and \
(end is None or end >= start_date)
result = []
for currency_code, start, end, is_tender in curs:
if start:
start = date_(*start)
if end:
end = date_(*end)
if ((is_tender and tender) or
(not is_tender and non_tender)) and _is_active(start, end):
if include_details:
result.append({
'currency': currency_code,
'from': start,
'to': end,
'tender': is_tender,
})
else:
result.append(currency_code)
return result
开发者ID:marcosptf,项目名称:fedora,代码行数:88,代码来源:numbers.py
示例13: format_currency
def format_currency(number, currency, format=None, locale=LC_NUMERIC,
currency_digits=True, format_type='standard'):
u"""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'US$\\xa01.099,98'
>>> format_currency(1099.98, 'EUR', locale='de_DE')
u'1.099,98\\xa0\\u20ac'
The format 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'\xa4\xa4 #,##0.00', locale='en_US')
u'EUR 1,099.98'
>>> format_currency(1099.98, 'EUR', u'#,##0.00 \xa4\xa4\xa4', locale='en_US')
u'1,099.98 euros'
Currencies usually have a specific number of decimal digits. This function
favours that information over the given format:
>>> format_currency(1099.98, 'JPY', locale='en_US')
u'\\xa51,100'
>>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES')
u'1.100'
However, the number of decimal digits can be overriden from the currency
information, by setting the last parameter to ``False``:
>>> format_currency(1099.98, 'JPY', locale='en_US', currency_digits=False)
u'\\xa51,099.98'
>>> format_currency(1099.98, 'COP', u'#,##0.00', locale='es_ES', currency_digits=False)
u'1.099,98'
If a format is not specified the type of currency format to use
from the locale can be specified:
>>> format_currency(1099.98, 'EUR', locale='en_US', format_type='standard')
u'\\u20ac1,099.98'
When the given currency format type is not available, an exception is
raised:
>>> format_currency('1099.98', 'EUR', locale='root', format_type='unknown')
Traceback (most recent call last):
...
UnknownCurrencyFormatError: "'unknown' is not a known currency format type"
:param number: the number to format
:param currency: the currency code
:param format: the format string to use
:param locale: the `Locale` object or locale identifier
:param currency_digits: use the currency's number of decimal digits
:param format_type: the currency format type to use
"""
locale = Locale.parse(locale)
if format:
pattern = parse_pattern(format)
else:
try:
pattern = locale.currency_formats[format_type]
except KeyError:
raise UnknownCurrencyFormatError("%r is not a known currency format"
" type" % format_type)
if currency_digits:
fractions = get_global('currency_fractions')
try:
digits = fractions[currency][0]
except KeyError:
digits = fractions['DEFAULT'][0]
frac = (digits, digits)
else:
frac = None
return pattern.apply(number, locale, currency=currency, force_frac=frac)
开发者ID:marcosptf,项目名称:fedora,代码行数:77,代码来源:numbers.py
示例14: test_get_global
def test_get_global():
assert core.get_global('zone_aliases')['UTC'] == 'Etc/GMT'
assert core.get_global('zone_territories')['Europe/Berlin'] == 'DE'
开发者ID:dstanek,项目名称:babel,代码行数:3,代码来源:test_core.py
示例15: get_global
except ImportError:
try:
import winreg
except ImportError:
winreg = None
from babel.core import get_global
import pytz
# When building the cldr data on windows this module gets imported.
# Because at that point there is no global.dat yet this call will
# fail. We want to catch it down in that case then and just assume
# the mapping was empty.
try:
tz_names = get_global('windows_zone_mapping')
except RuntimeError:
tz_names = {}
def valuestodict(key):
"""Convert a registry key's values to a dictionary."""
dict = {}
size = winreg.QueryInfoKey(key)[1]
for i in range(size):
data = winreg.EnumValue(key, i)
dict[data[0]] = data[1]
return dict
def get_localzone_name():
开发者ID:marcosptf,项目名称:fedora,代码行数:31,代码来源:_win32.py
示例16: get_timezone_location
def get_timezone_location(dt_or_tzinfo=None, locale=LC_TIME):
"""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 assocaited with the time zone:
>>> from pytz import timezone
>>> tz = timezone('America/St_Johns')
>>> get_timezone_location(tz, locale='de_DE')
u"Kanada (St. John's)"
>>> tz = timezone('America/Mexico_City')
>>> get_timezone_location(tz, locale='de_DE')
u'Mexiko (Mexiko-Stadt)'
If the timezone is associated with a country that uses only a single
timezone, just the localized country name is returned:
>>> tz = timezone('Europe/Berlin')
>>> get_timezone_name(tz, locale='de_DE')
u'Deutschland'
:param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines
the timezone; if `None`, the current date and time in
UTC is assumed
:param locale: the `Locale` object, or a locale string
:return: the localized timezone name using location format
:rtype: `unicode`
:since: version 0.9
"""
if dt_or_tzinfo is None or isinstance(dt_or_tzinfo, (int, long)):
dt = None
tzinfo = UTC
elif isinstance(dt_or_tzinfo, (datetime, time)):
dt = dt_or_tzinfo
if dt.tzinfo is not None:
tzinfo = dt.tzinfo
else:
tzinfo = UTC
else:
dt = None
tzinfo = dt_or_tzinfo
locale = Locale.parse(locale)
if hasattr(tzinfo, "zone"):
zone = tzinfo.zone
else:
zone = tzinfo.tzname(dt or datetime.utcnow())
# Get the canonical time-zone code
zone = get_global("zone_aliases").get(zone, zone)
info = locale.time_zones.get(zone, {})
# Otherwise, if there is only one timezone for the country, return the
# localized country name
region_format = locale.zone_formats["region"]
territory = get_global("zone_territories").get(zone)
if territory not in locale.territories:
territory = "ZZ" # invalid/unknown
territory_name = locale.territories[territory]
if territory and len(get_global("territory_zones").get(territory, [])) == 1:
return region_format % (territory_name)
# Otherwise, include the city in the output
fallback_format = locale.zone_formats["fallback"]
if "city" in info:
city_name = info["city"]
else:
metazone = get_global("meta_zones").get(zone)
metazone_info = locale.meta_zones.get(metazone, {})
if "city" in metazone_info:
city_name = metainfo["city"]
elif "/" in zone:
city_name = zone.split("/", 1)[1].replace("_", " ")
else:
city_name = zone.replace("_", " ")
return region_format % (fallback_format % {"0": city_name, "1": territory_name})
开发者ID:miracle2k,项目名称:babel,代码行数:78,代码来源:dates.py
示例17: get_timezone_location
def get_timezone_location(dt_or_tzinfo=None, locale=LC_TIME):
"""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'
.. versionadded:: 0.9
:param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines
the timezone; if `None`, the current date and time in
UTC is assumed
:param locale: the `Locale` object, or a locale string
:return: the localized timezone name using location format
"""
if dt_or_tzinfo is None:
dt = datetime.now()
tzinfo = LOCALTZ
elif isinstance(dt_or_tzinfo, string_types):
dt = None
tzinfo = get_timezone(dt_or_tzinfo)
elif isinstance(dt_or_tzinfo, integer_types):
dt = None
tzinfo = UTC
elif isinstance(dt_or_tzinfo, (datetime, time)):
dt = dt_or_tzinfo
if dt.tzinfo is not None:
tzinfo = dt.tzinfo
else:
tzinfo = UTC
else:
dt = None
tzinfo = dt_or_tzinfo
locale = Locale.parse(locale)
if hasattr(tzinfo, 'zone'):
zone = tzinfo.zone
else:
zone = tzinfo.tzname(dt or datetime.utcnow())
# Get the canonical time-zone code
zone = get_global('zone_aliases').get(zone, zone)
info = locale.time_zones.get(zone, {})
# Otherwise, if there is only one timezone for the country, return the
# localized country name
region_format = locale.zone_formats['region']
territory = get_global('zone_territories').get(zone)
if territory not in locale.territories:
territory = 'ZZ' # invalid/unknown
territory_name = locale.territories[territory]
if territory and len(get_global('territory_zones').get(territory, [])) == 1:
return region_format % (territory_name)
# Otherwise, include the city in the output
fallback_format = locale.zone_formats['fallback']
if 'city' in info:
city_name = info['city']
else:
metazone = get_global('meta_zones').get(zone)
metazone_info = locale.meta_zones.get(metazone, {})
if 'city' in metazone_info:
city_name = metazone_info['city']
elif '/' in zone:
city_name = zone.split('/', 1)[1].replace('_', ' ')
else:
city_name = zone.replace('_', ' ')
return region_format % (fallback_format % {
'0': city_name,
'1': territory_name
})
开发者ID:eavae,项目名称:mlang,代码行数:86,代码来源:dates.py
示例18: get_timezone_name
#.........这里部分代码省略.........
>>> 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
<http://www.unicode.org/reports/tr35/#Time_Zone_Fallback>`_
.. versionadded:: 0.9
.. versionchanged:: 1.0
Added `zone_variant` support.
:param 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
:param width: either "long" or "short"
:param uncommon: deprecated and ignored
:param 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'``.
:param locale: the `Locale` object, or a locale string
"""
if dt_or_tzinfo is None:
dt = datetime.now()
tzinfo = LOCALTZ
elif isinstance(dt_or_tzinfo, string_types):
dt = None
tzinfo = get_timezone(dt_or_tzinfo)
elif isinstance(dt_or_tzinfo, integer_types):
dt = None
tzinfo = UTC
elif isinstance(dt_or_tzinfo, (datetime, time)):
dt = dt_or_tzinfo
if dt.tzinfo is not None:
tzinfo = dt.tzinfo
else:
tzinfo = UTC
else:
dt = None
tzinfo = dt_or_tzinfo
locale = Locale.parse(locale)
if hasattr(tzinfo, 'zone'):
zone = tzinfo.zone
else:
zone = tzinfo.tzname(dt)
if zone_variant is None:
if dt is None:
zone_variant = 'generic'
else:
dst = tzinfo.dst(dt)
if dst:
zone_variant = 'daylight'
else:
zone_variant = 'standard'
else:
if zone_variant not in ('generic', 'standard', 'daylight'):
raise ValueError('Invalid zone variation')
# Get the canonical time-zone code
zone = get_global('zone_aliases').get(zone, zone)
info = locale.time_zones.get(zone, {})
# Try explicitly translated zone names first
if width in info:
if zone_variant in info[width]:
return info[width][zone_variant]
metazone = get_global('meta_zones').get(zone)
if metazone:
metazone_info = locale.meta_zones.get(metazone, {})
if width in metazone_info:
if zone_variant in metazone_info[width]:
return metazone_info[width][zone_variant]
# If we have a concrete datetime, we assume that the result can't be
# independent of daylight savings time, so we return the GMT offset
if dt is not None:
return get_timezone_gmt(dt, width=width, locale=locale)
return get_timezone_location(dt_or_tzinfo, locale=locale)
开发者ID:eavae,项目名称:mlang,代码行数:101,代码来源:dates.py
示例19: get_timezone_name
def get_timezone_name(dt_or_tzinfo=None, width='long', uncommon=False,
locale=LC_TIME):
r"""Return the localized display name for the given timezone. The timezone
may be specified using a ``datetime`` or `tzinfo` object.
>>> from pytz import timezone
>>> dt = time(15, 30, tzinfo=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 = 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 = timezone('Europe/Berlin')
>>> get_timezone_name(tz, locale='de_DE')
u'Deutschland'
>>> get_timezone_name(tz, locale='pt_BR')
u'Hor\xe1rio Alemanha'
On the other hand, if the country uses multiple timezones, the city is also
included in the representation:
>>> tz = timezone('America/St_Johns')
>>> get_timezone_name(tz, locale='de_DE')
u"Kanada (St. John's)"
The `uncommon` parameter can be set to `True` to enable the use of timezone
representations that are not commonly used by the requested locale. For
example, while in French the central European timezone is usually
abbreviated as "HEC", in Canadian French, this abbreviation is not in
common use, so a generic name would be chosen by default:
>>> tz = timezone('Europe/Paris')
>>> get_timezone_name(tz, 'short', locale='fr_CA')
u'France'
>>> get_timezone_name(tz, 'short', uncommon=True, locale='fr_CA')
u'HEC'
:param 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
:param width: either "long" or "short"
:param uncommon: whether even uncommon timezone abbreviations should be used
:param locale: the `Locale` object, or a locale string
:return: the timezone display name
:rtype: `unicode`
:since: version 0.9
:see: `LDML Appendix J: Time Zone Display Names
<http://www.unicode.org/reports/tr35/#Time_Zone_Fallback>`_
"""
if dt_or_tzinfo is None or isinstance(dt_or_tzinfo, (int, long)):
dt = None
tzinfo = UTC
elif isinstance(dt_or_tzinfo, (datetime, time)):
dt = dt_or_tzinfo
if dt.tzinfo is not None:
tzinfo = dt.tzinfo
else:
tzinfo = UTC
else:
dt = None
tzinfo = dt_or_tzinfo
locale = Locale.parse(locale)
if hasattr(tzinfo, 'zone'):
zone = tzinfo.zone
else:
zone = tzinfo.tzname(dt)
# Get the canonical time-zone code
zone = get_global('zone_aliases').get(zone, zone)
info = locale.time_zones.get(zone, {})
# Try explicitly translated zone names first
if width in info:
if dt is None:
field = 'generic'
else:
dst = tzinfo.dst(dt)
if dst is None:
field = 'generic'
elif dst == 0:
field = 'standard'
else:
#.........这里部分代码省略.........
开发者ID:10sr,项目名称:hue,代码行数:101,代码来源:dates.py
注:本文中的babel.core.get_global函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论