python类UnknownTimeZoneError()的实例源码

gcal_sync.py 文件源码 项目:hashtagtodo-open 作者: slackpad 项目源码 文件源码 阅读 14 收藏 0 点赞 0 评论 0
def safe_timezone(time_zone):
    try:
        return pytz.timezone(time_zone)
    except pytz.UnknownTimeZoneError:
        # This is a hack! We need to audit for these and clean them up.
        print 'BAD_TZ: %s' % time_zone
        return pytz.timezone('America/Los_Angeles')
croninfo.py 文件源码 项目:Intranet-Penetration 作者: yuxiaokui 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def Validate(self, value, key=None):
    """Validates a timezone."""
    if value is None:

      return
    if not isinstance(value, basestring):
      raise TypeError('timezone must be a string, not \'%r\'' % type(value))
    if pytz is None:

      return value
    try:
      pytz.timezone(value)
    except pytz.UnknownTimeZoneError:
      raise validation.ValidationError('timezone \'%s\' is unknown' % value)
    except IOError:


      return value
    except:


      unused_e, v, t = sys.exc_info()
      logging.warning('pytz raised an unexpected error: %s.\n' % (v) +
                      'Traceback:\n' + '\n'.join(traceback.format_tb(t)))
      raise
    return value
croninfo.py 文件源码 项目:MKFQ 作者: maojingios 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def Validate(self, value, key=None):
    """Validates a timezone."""
    if value is None:

      return
    if not isinstance(value, basestring):
      raise TypeError('timezone must be a string, not \'%r\'' % type(value))
    if pytz is None:

      return value
    try:
      pytz.timezone(value)
    except pytz.UnknownTimeZoneError:
      raise validation.ValidationError('timezone \'%s\' is unknown' % value)
    except IOError:


      return value
    except:


      unused_e, v, t = sys.exc_info()
      logging.warning('pytz raised an unexpected error: %s.\n' % (v) +
                      'Traceback:\n' + '\n'.join(traceback.format_tb(t)))
      raise
    return value
prop.py 文件源码 项目:iCalVerter 作者: amsysuk 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def from_ical(ical, timezone=None):
        tzinfo = None
        if timezone:
            try:
                tzinfo = pytz.timezone(timezone)
            except pytz.UnknownTimeZoneError:
                tzinfo = _timezone_cache.get(timezone, None)

        try:
            timetuple = (
                int(ical[:4]),  # year
                int(ical[4:6]),  # month
                int(ical[6:8]),  # day
                int(ical[9:11]),  # hour
                int(ical[11:13]),  # minute
                int(ical[13:15]),  # second
            )
            if tzinfo:
                return tzinfo.localize(datetime(*timetuple))
            elif not ical[15:]:
                return datetime(*timetuple)
            elif ical[15:16] == 'Z':
                return pytz.utc.localize(datetime(*timetuple))
            else:
                raise ValueError(ical)
        except:
            raise ValueError('Wrong datetime format: %s' % ical)
test_preprocess.py 文件源码 项目:catalyst 作者: enigmampc 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_ensure_timezone(self):
        @preprocess(tz=ensure_timezone)
        def f(tz):
            return tz

        valid = {
            'utc',
            'EST',
            'US/Eastern',
        }
        invalid = {
            # unfortunatly, these are not actually timezones (yet)
            'ayy',
            'lmao',
        }

        # test coercing from string
        for tz in valid:
            self.assertEqual(f(tz), pytz.timezone(tz))

        # test pass through of tzinfo objects
        for tz in map(pytz.timezone, valid):
            self.assertEqual(f(tz), tz)

        # test invalid timezone strings
        for tz in invalid:
            self.assertRaises(pytz.UnknownTimeZoneError, f, tz)
astral.py 文件源码 项目:respeaker_virtualenv 作者: respeaker 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def tz(self):
        """Time zone information."""

        try:
            tz = pytz.timezone(self.timezone)
            return tz
        except pytz.UnknownTimeZoneError:
            raise AstralError('Unknown timezone \'%s\'' % self.timezone)
timezones.py 文件源码 项目:py-kms 作者: SystemRage 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def detect_timezone():
  """Try and detect the timezone that Python is currently running in.

  We have a bunch of different methods for trying to figure this out (listed in
  order they are attempted).
    * Try and find /etc/timezone file (with timezone name).
    * Try and find /etc/localtime file (with timezone data).
    * Try and match a TZ to the current dst/offset/shortname.

  Returns:
    The detected local timezone as a tzinfo object

  Raises:
    pytz.UnknownTimeZoneError: If it was unable to detect a timezone.
  """

  tz = _detect_timezone_etc_timezone()
  if tz is not None:
    return tz

  tz = _detect_timezone_etc_localtime()
  if tz is not None:
    return tz

  # Next we try and use a similiar method to what PHP does.
  # We first try to search on time.tzname, time.timezone, time.daylight to
  # match a pytz zone.
  warnings.warn("Had to fall back to worst detection method (the 'PHP' "
                "method).")

  tz = _detect_timezone_php()
  if tz is not None:
    return tz

  raise pytz.UnknownTimeZoneError("Unable to detect your timezone!")
timezones.py 文件源码 项目:py-kms 作者: SystemRage 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _detect_timezone_etc_timezone():
  if os.path.exists("/etc/timezone"):
    try:
      tz = file("/etc/timezone").read().strip()
      try:
        return pytz.timezone(tz)
      except (IOError, pytz.UnknownTimeZoneError), ei:
        warnings.warn("Your /etc/timezone file references a timezone (%r) that"
                      " is not valid (%r)." % (tz, ei))

    # Problem reading the /etc/timezone file
    except IOError, eo:
      warnings.warn("Could not access your /etc/timezone file: %s" % eo)
_win32.py 文件源码 项目:chalktalk_docs 作者: loremIpsum1771 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _get_localzone():
    if winreg is None:
        raise pytz.UnknownTimeZoneError(
            'Runtime support not available')
    return pytz.timezone(get_localzone_name())
catchpoint.py 文件源码 项目:catchpoint_opentsdb_bridge 作者: ns1 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def _format_time(self, startTime, endTime, tz):
        """
        Format "now" time to actual UTC time and set microseconds to 0.

        - startTime: start time of the requested data (least recent).
        - endTime: end time of the requested data (most recent).
        - tz: Timezone in tz database format (Catchpoint uses a different format).
        """
        if endTime is not None and startTime is not None:
            if endTime == "now":
                if not isinstance(startTime, int) and startTime >= 0:
                    msg = "When using relative times, startTime must be a negative number (number of minutes minus 'now')."
                    sys.exit(msg)
                try:
                    endTime = datetime.datetime.now(pytz.timezone(tz))
                    endTime = endTime.replace(microsecond=0)
                except pytz.UnknownTimeZoneError:
                    msg = "Unknown Timezone '{0}'\nUse tz database format: http://en.wikipedia.org/wiki/List_of_tz_database_time_zones" .format(tz)
                    sys.exit(msg)
                startTime = endTime + datetime.timedelta(minutes=int(startTime))
                startTime = startTime.strftime('%Y-%m-%dT%H:%M:%S')
                endTime = endTime.strftime('%Y-%m-%dT%H:%M:%S')
                self._debug("endTime: " + str(endTime))
                self._debug("startTime: " + str(startTime))

        return startTime, endTime
gui_utils.py 文件源码 项目:esdc-ce 作者: erigones 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def local_schedule(schedule_or_webdata, tz_name):
    if isinstance(schedule_or_webdata, dict):
        schedule = schedule_or_webdata['schedule'].split()
        is_dict = True
    else:
        schedule = schedule_or_webdata.split()
        is_dict = False

    try:
        hour = schedule[1]
        assert '*' not in hour
    except (IndexError, AssertionError):
        return schedule_or_webdata

    try:
        tz = pytz.timezone(tz_name)
    except pytz.UnknownTimeZoneError:
        return schedule_or_webdata

    def to_local(match):
        num = int(match.group(0))
        now = datetime.utcnow().replace(hour=num, tzinfo=pytz.utc)
        return str(tz.normalize(now).hour)

    try:
        schedule[1] = re.sub(r'(\d+)', to_local, hour)
    except ValueError:
        return schedule_or_webdata
    else:
        new_schedule = ' '.join(schedule)

    if is_dict:
        schedule_or_webdata['schedule'] = new_schedule
        return schedule_or_webdata
    return new_schedule
pytz_support.py 文件源码 项目:isf 作者: w3h 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def __getitem__(self, key):
        name = self._zmap.get(key.lower(), key)  # fallback to key
        try:
            return Timezone(pytz.timezone(name))
        except pytz.UnknownTimeZoneError:
            try:
                return Timezone(_numeric_timezones[name])
            except KeyError:
                raise DateTimeError('Unrecognized timezone: %s' % key)
astral.py 文件源码 项目:astral 作者: sffjunkie 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def tz(self):
        """Time zone information."""

        try:
            tz = pytz.timezone(self.timezone)
            return tz
        except pytz.UnknownTimeZoneError:
            raise AstralError('Unknown timezone \'%s\'' % self.timezone)
croninfo.py 文件源码 项目:xxNet 作者: drzorm 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def Validate(self, value, key=None):
    """Validates a timezone."""
    if value is None:

      return
    if not isinstance(value, basestring):
      raise TypeError('timezone must be a string, not \'%r\'' % type(value))
    if pytz is None:

      return value
    try:
      pytz.timezone(value)
    except pytz.UnknownTimeZoneError:
      raise validation.ValidationError('timezone \'%s\' is unknown' % value)
    except IOError:


      return value
    except:


      unused_e, v, t = sys.exc_info()
      logging.warning('pytz raised an unexpected error: %s.\n' % (v) +
                      'Traceback:\n' + '\n'.join(traceback.format_tb(t)))
      raise
    return value
icalendar.py 文件源码 项目:python-card-me 作者: tBaxter 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def getTzid(tzid, smart=True):
    """Return the tzid if it exists, or None."""
    tz = __tzidMap.get(toUnicode(tzid), None)
    if smart and tzid and not tz:
        try:
            from pytz import timezone, UnknownTimeZoneError
            try:
                tz = timezone(tzid)
                registerTzid(toUnicode(tzid), tz)
            except UnknownTimeZoneError:
                pass
        except ImportError:
            pass
    return tz
croninfo.py 文件源码 项目:Deploy_XXNET_Server 作者: jzp820927 项目源码 文件源码 阅读 86 收藏 0 点赞 0 评论 0
def Validate(self, value, key=None):
    """Validates a timezone."""
    if value is None:

      return
    if not isinstance(value, basestring):
      raise TypeError('timezone must be a string, not \'%r\'' % type(value))
    if pytz is None:

      return value
    try:
      pytz.timezone(value)
    except pytz.UnknownTimeZoneError:
      raise validation.ValidationError('timezone \'%s\' is unknown' % value)
    except IOError:


      return value
    except:


      unused_e, v, t = sys.exc_info()
      logging.warning('pytz raised an unexpected error: %s.\n' % (v) +
                      'Traceback:\n' + '\n'.join(traceback.format_tb(t)))
      raise
    return value
_win32.py 文件源码 项目:enkiWS 作者: juliettef 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _get_localzone():
    if winreg is None:
        raise pytz.UnknownTimeZoneError(
            'Runtime support not available')
    return pytz.timezone(get_localzone_name())
views.py 文件源码 项目:morpheus 作者: tutorcruncher 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _strftime(self, ts):
        dt_tz = self.request.query.get('dttz') or 'utc'
        try:
            dt_tz = pytz.timezone(dt_tz)
        except pytz.UnknownTimeZoneError:
            raise HTTPBadRequest(text=f'unknown timezone: "{dt_tz}"')

        dt_fmt = self.request.query.get('dtfmt') or '%a %Y-%m-%d %H:%M'
        return from_unix_ms(ts, 0).astimezone(dt_tz).strftime(dt_fmt)
croninfo.py 文件源码 项目:Docker-XX-Net 作者: kuanghy 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def Validate(self, value, key=None):
    """Validates a timezone."""
    if value is None:

      return
    if not isinstance(value, basestring):
      raise TypeError('timezone must be a string, not \'%r\'' % type(value))
    if pytz is None:

      return value
    try:
      pytz.timezone(value)
    except pytz.UnknownTimeZoneError:
      raise validation.ValidationError('timezone \'%s\' is unknown' % value)
    except IOError:


      return value
    except:


      unused_e, v, t = sys.exc_info()
      logging.warning('pytz raised an unexpected error: %s.\n' % (v) +
                      'Traceback:\n' + '\n'.join(traceback.format_tb(t)))
      raise
    return value
forms.py 文件源码 项目:railgun 作者: xin-xinhanggao 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def validate_timezone(form, field):
        """Validate whether the user provided timezone is a valid timezone.
        Lists of valid timezones can be found on `Wikipedia
        <http://en.wikipedia.org/wiki/List_of_tz_database_time_zones>`_
        """
        try:
            timezone(field.data)
        except UnknownTimeZoneError:
            raise ValidationError(_("Please enter a valid timezone."))


问题


面经


文章

微信
公众号

扫码关注公众号