當前位置: 首頁>>代碼示例>>Python>>正文


Python pytz.UnknownTimeZoneError方法代碼示例

本文整理匯總了Python中pytz.UnknownTimeZoneError方法的典型用法代碼示例。如果您正苦於以下問題:Python pytz.UnknownTimeZoneError方法的具體用法?Python pytz.UnknownTimeZoneError怎麽用?Python pytz.UnknownTimeZoneError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pytz的用法示例。


在下文中一共展示了pytz.UnknownTimeZoneError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: __init__

# 需要導入模塊: import pytz [as 別名]
# 或者: from pytz import UnknownTimeZoneError [as 別名]
def __init__(self, **params):
        try:
            timezone = pytz.timezone(params.pop('timezone', None))
        except (pytz.UnknownTimeZoneError, AttributeError):
            timezone = pytz.UTC

        for field in self.__annotations__:
            api_field = undo_snake_case_key(field)
            if self.__annotations__[field] == datetime:
                params[api_field] = get_datetime_from_unix(
                    params.get(api_field),
                    timezone
                )

            if api_field in params:
                setattr(self, field, params.get(api_field))
            else:
                setattr(self, field, None) 
開發者ID:Detrous,項目名稱:darksky,代碼行數:20,代碼來源:base.py

示例2: tz_from_string

# 需要導入模塊: import pytz [as 別名]
# 或者: from pytz import UnknownTimeZoneError [as 別名]
def tz_from_string(_option, _opt_str, value, parser):
    """Stores a tzinfo object from a string"""
    if value is not None:
        if value[0] in ['+', '-']:
            # Handed a numeric offset, create an OffsetTzInfo
            valarray = [value[i:i + 2] for i in range(1, len(value), 2)]
            multipliers = [3600, 60]
            offset = 0
            for i in range(min(len(valarray), len(multipliers))):
                offset += int(valarray[i]) * multipliers[i]
            if value[0] == '-':
                offset = -offset
            timezone = OffsetTzInfo(offset = offset)
        else:
            # Value is a lookup, choose pytz over time.tzset
            if tz_pytz:
                try:
                    timezone = pytz.timezone(value)
                except pytz.UnknownTimeZoneError:
                    debug.error("Unknown display timezone specified")
            else:
                if not hasattr(time, 'tzset'):
                    debug.error("This operating system doesn't support tzset, please either specify an offset (eg. +1000) or install pytz")
                timezone = value
        parser.values.tz = timezone 
開發者ID:virtualrealitysystems,項目名稱:aumfor,代碼行數:27,代碼來源:timefmt.py

示例3: _tz_from_env

# 需要導入模塊: import pytz [as 別名]
# 或者: from pytz import UnknownTimeZoneError [as 別名]
def _tz_from_env(tzenv):
    if tzenv[0] == ':':
        tzenv = tzenv[1:]

    # TZ specifies a file
    if os.path.exists(tzenv):
        with open(tzenv, 'rb') as tzfile:
            return pytz.tzfile.build_tzinfo('local', tzfile)

    # TZ specifies a zoneinfo zone.
    try:
        tz = pytz.timezone(tzenv)
        # That worked, so we return this:
        return tz
    except pytz.UnknownTimeZoneError:
        raise pytz.UnknownTimeZoneError(
            "tzlocal() does not support non-zoneinfo timezones like %s. \n"
            "Please use a timezone in the form of Continent/City") 
開發者ID:Schibum,項目名稱:sndlatr,代碼行數:20,代碼來源:_unix.py

示例4: get_timezone

# 需要導入模塊: import pytz [as 別名]
# 或者: from pytz import UnknownTimeZoneError [as 別名]
def get_timezone(zone=None):
    """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 :exc:`LookupError` is raised.  If `zone`
    is ``None`` a local zone object is returned.

    :param zone: the name of the timezone to look up.  If a timezone object
                 itself is passed in, mit's returned unchanged.
    """
    if zone is None:
        return LOCALTZ
    if not isinstance(zone, string_types):
        return zone
    try:
        return _pytz.timezone(zone)
    except _pytz.UnknownTimeZoneError:
        raise LookupError('Unknown timezone %s' % zone) 
開發者ID:Schibum,項目名稱:sndlatr,代碼行數:21,代碼來源:dates.py

示例5: test_env

# 需要導入模塊: import pytz [as 別名]
# 或者: from pytz import UnknownTimeZoneError [as 別名]
def test_env(self):
        tz_harare = tzlocal.unix._tz_from_env(':Africa/Harare')
        self.assertEqual(tz_harare.zone, 'Africa/Harare')

        # Some Unices allow this as well, so we must allow it:
        tz_harare = tzlocal.unix._tz_from_env('Africa/Harare')
        self.assertEqual(tz_harare.zone, 'Africa/Harare')

        local_path = os.path.split(__file__)[0]
        tz_local = tzlocal.unix._tz_from_env(':' + os.path.join(local_path, 'test_data', 'Harare'))
        self.assertEqual(tz_local.zone, 'local')
        # Make sure the local timezone is the same as the Harare one above.
        # We test this with a past date, so that we don't run into future changes
        # of the Harare timezone.
        dt = datetime(2012, 1, 1, 5)
        self.assertEqual(tz_harare.localize(dt), tz_local.localize(dt))

        # Non-zoneinfo timezones are not supported in the TZ environment.
        self.assertRaises(pytz.UnknownTimeZoneError, tzlocal.unix._tz_from_env, 'GMT+03:00') 
開發者ID:taxigps,項目名稱:xbmc-addons-chinese,代碼行數:21,代碼來源:tests.py

示例6: parse_timezone

# 需要導入模塊: import pytz [as 別名]
# 或者: from pytz import UnknownTimeZoneError [as 別名]
def parse_timezone(tzname, default=None):
    if tzname:
        # accept valid pytz names like US/Pacific
        try:
            return pytz_timezone(tzname)
        except UnknownTimeZoneError:
            pass
        # else check if it is a short name
        for zone in all_timezones:
            if tzname == zone.split('/')[-1]:
                return pytz_timezone(zone)
        # else check if it is one of out Timezone
        try:
            tz = TimeZone.objects.get(time_zone=tzname)
            return timezone(timedelta(seconds=tz.tzoffset))
        except TimeZone.DoesNotExist:
            pass

        logging.error('Unknown timezone {}'.format(tzname))
    if default:
        return pytz_timezone(default)
    return None 
開發者ID:opentaps,項目名稱:opentaps_seas,代碼行數:24,代碼來源:utils.py

示例7: localize_timezone

# 需要導入模塊: import pytz [as 別名]
# 或者: from pytz import UnknownTimeZoneError [as 別名]
def localize_timezone(date_time, tz_string):
    if date_time.tzinfo:
        return date_time

    tz = None

    try:
        tz = timezone(tz_string)
    except UnknownTimeZoneError as e:
        for name, info in _tz_offsets:
            if info['regex'].search(' %s' % tz_string):
                tz = StaticTzInfo(name, info['offset'])
                break
        else:
            raise e

    return tz.localize(date_time) 
開發者ID:scrapinghub,項目名稱:dateparser,代碼行數:19,代碼來源:__init__.py

示例8: to_python

# 需要導入模塊: import pytz [as 別名]
# 或者: from pytz import UnknownTimeZoneError [as 別名]
def to_python(self, value):
        """Returns a datetime.tzinfo instance for the value."""
        # pylint: disable=newstyle
        value = super(TimeZoneField, self).to_python(value)

        if not value:
            return value

        try:
            return pytz.timezone(str(value))
        except pytz.UnknownTimeZoneError:
            raise ValidationError(
                message=self.error_messages['invalid'],
                code='invalid',
                params={'value': value}
            )

    # pylint: disable=E0239 
開發者ID:michaeljohnbarr,項目名稱:django-timezone-utils,代碼行數:20,代碼來源:fields.py

示例9: _get_populate_from

# 需要導入模塊: import pytz [as 別名]
# 或者: from pytz import UnknownTimeZoneError [as 別名]
def _get_populate_from(self, model_instance):
        """
        Retrieves the timezone or None from the `populate_from` attribute.
        """

        if hasattr(self.populate_from, '__call__'):
            tz = self.populate_from(model_instance)
        else:
            from_attr = getattr(model_instance, self.populate_from)
            tz = callable(from_attr) and from_attr() or from_attr

        try:
            tz = pytz.timezone(str(tz))
        except pytz.UnknownTimeZoneError:
            # It was a valiant effort. Resistance is futile.
            raise

        # If we have a timezone, set the instance's timezone attribute
        self.timezone = tz

        return tz 
開發者ID:michaeljohnbarr,項目名稱:django-timezone-utils,代碼行數:23,代碼來源:fields.py

示例10: get_duration_with_tz

# 需要導入模塊: import pytz [as 別名]
# 或者: from pytz import UnknownTimeZoneError [as 別名]
def get_duration_with_tz(self):
        if self.duration == 0:
            return 0
        elif isinstance(self.duration, datetime.datetime):
            dt = self.duration
            if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None:
                dt = pytz.utc.localize(dt)
            if isinstance(self.duration_tz, float):
                tz = possible_timezones(self.duration_tz, common_only=True)
                if not tz:
                    tz = pytz.timezone('UTC')
                else:
                    # choose one valid timezone with the offset
                    try:
                        tz = pytz.timezone(tz[0])
                    except UnknownTimeZoneError:
                        tz = pytz.UTC
            else:
                try:
                    tz = pytz.timezone(self.duration_tz)
                except UnknownTimeZoneError:
                    tz = pytz.UTC

            return dt.astimezone(tz) 
開發者ID:matnad,項目名稱:pollmaster,代碼行數:26,代碼來源:poll.py

示例11: _tz_from_env

# 需要導入模塊: import pytz [as 別名]
# 或者: from pytz import UnknownTimeZoneError [as 別名]
def _tz_from_env(tzenv):
    if tzenv[0] == ':':
        tzenv = tzenv[1:]

    # TZ specifies a file
    if os.path.isabs(tzenv) and os.path.exists(tzenv):
        with open(tzenv, 'rb') as tzfile:
            return pytz.tzfile.build_tzinfo('local', tzfile)

    # TZ specifies a zoneinfo zone.
    try:
        tz = pytz.timezone(tzenv)
        # That worked, so we return this:
        return tz
    except pytz.UnknownTimeZoneError:
        raise pytz.UnknownTimeZoneError(
            "tzlocal() does not support non-zoneinfo timezones like %s. \n"
            "Please use a timezone in the form of Continent/City") 
開發者ID:morpheus65535,項目名稱:bazarr,代碼行數:20,代碼來源:unix.py

示例12: prepare

# 需要導入模塊: import pytz [as 別名]
# 或者: from pytz import UnknownTimeZoneError [as 別名]
def prepare(self):
    self.session = await self.update_session()
    if 'domain_id' in self.request.match_info:
      self.domain_id = self.request.match_info.pop('domain_id')
    if 'uid' in self.session:
      uid = self.session['uid']
      self.user, self.domain, self.domain_user, bdoc = await asyncio.gather(
          user.get_by_uid(uid),
          domain.get(self.domain_id),
          domain.get_user(self.domain_id, uid),
          blacklist.get(self.remote_ip))
      if not self.user:
        raise error.UserNotFoundError(uid)
      if not self.domain_user:
        self.domain_user = {}
    else:
      self.domain, bdoc = await asyncio.gather(
          domain.get(self.domain_id), blacklist.get(self.remote_ip))
    self.view_lang = self.get_setting('view_lang')
    try:
      self.timezone = pytz.timezone(self.get_setting('timezone'))
    except pytz.UnknownTimeZoneError:
      pass
    self.locale = locale.get(self.view_lang)
    self.datetime_stamp = _datetime_stamp
    if bdoc:
      raise error.BlacklistedError(self.remote_ip)
    if not self.GLOBAL and not self.has_priv(builtin.PRIV_VIEW_ALL_DOMAIN):
      self.check_perm(builtin.PERM_VIEW) 
開發者ID:vijos,項目名稱:vj4,代碼行數:31,代碼來源:base.py

示例13: coerce_timezone

# 需要導入模塊: import pytz [as 別名]
# 或者: from pytz import UnknownTimeZoneError [as 別名]
def coerce_timezone(zone):
    try:
        return pytz.timezone(zone)
    except pytz.UnknownTimeZoneError:
        raise ValidationError(
            _('Unknown timezone.'), code='invalid'
        ) 
開發者ID:charettes,項目名稱:django-sundial,代碼行數:9,代碼來源:utils.py

示例14: _get_localzone

# 需要導入模塊: import pytz [as 別名]
# 或者: from pytz import UnknownTimeZoneError [as 別名]
def _get_localzone():
    if winreg is None:
        raise pytz.UnknownTimeZoneError(
            'Runtime support not available')
    return pytz.timezone(get_localzone_name()) 
開發者ID:Schibum,項目名稱:sndlatr,代碼行數:7,代碼來源:_win32.py

示例15: __init__

# 需要導入模塊: import pytz [as 別名]
# 或者: from pytz import UnknownTimeZoneError [as 別名]
def __init__(self, *args, **kwargs):

        def coerce_to_pytz(val):
            try:
                return pytz.timezone(val)
            except pytz.UnknownTimeZoneError:
                raise ValidationError("Unknown time zone: '%s'" % val)

        defaults = {
            'coerce': coerce_to_pytz,
            'choices': [(tz, tz) for tz in pytz.common_timezones],
            'empty_value': None,
        }
        defaults.update(kwargs)
        super(TimeZoneFormField, self).__init__(*args, **defaults) 
開發者ID:dkarchmer,項目名稱:django-aws-template,代碼行數:17,代碼來源:forms.py


注:本文中的pytz.UnknownTimeZoneError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。