Beispiel #1
0
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)
    ['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 ((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
Beispiel #2
0
def test_get_global():
    assert core.get_global('zone_aliases')['UTC'] == 'Etc/GMT'
    assert core.get_global('zone_territories')['Europe/Berlin'] == 'DE'
Beispiel #3
0
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})
Beispiel #4
0
def get_timezone_name(dt_or_tzinfo=None, width="long", uncommon=False, locale=LC_TIME, zone_variant=None):
    r"""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
    <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)
Beispiel #5
0
except ImportError:
    try:
        import winreg
    except ImportError:
        winreg = None

from py3babel.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():