我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pytz.UnknownTimeZoneError()。
def _select_locale(self, request): supported = request.event.locales language = ( self._language_from_user(request, supported) or self._language_from_cookie(request, supported) or self._language_from_browser(request, supported) or request.event.locale ) translation.activate(language) request.LANGUAGE_CODE = translation.get_language() with suppress(pytz.UnknownTimeZoneError): tzname = request.event.timezone timezone.activate(pytz.timezone(tzname)) request.timezone = tzname
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")
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)
def _time(self, ctx): """Determine the current time in a timezone specified. The timezone is case sensitive as seen in [this list](https://pastebin.com/B5tLQdEY). **Usage:** `g_time <timezone> **Permission:** User""" umsg = ctx.message.content args = umsg.split(' ') if len(args) > 1: try: if args[1].startswith('GMT'): if args[1].startswith('GMT+'): t = args[1].replace('+', '-') elif args[1].startswith('GMT-'): t = args[1].replace('-', '+') tz = pytz.timezone('Etc/'+t) else: tz = pytz.timezone(args[1]) await ctx.send("The time in **{0}** is {1}".format(args[1], datetime.datetime.now(tz).strftime("`%H:%M:%S` on `%d-%b-%Y`"))) except pytz.UnknownTimeZoneError: await ctx.send('Couldn\'t find that timezone, make sure to use one from this list: <https://pastebin.com/B5tLQdEY>\nAlso remember that timezones are case sensitive.') else: await ctx.send(":x: Usage: `{}time <timezone>`".format(self.bot.command_prefix[0]))
def _select_locale(self, request): supported = request.event.locales if (hasattr(request, 'event') and request.event) else settings.LANGUAGES language = ( self._language_from_user(request, supported) or self._language_from_cookie(request, supported) or self._language_from_browser(request, supported) ) if hasattr(request, 'event') and request.event: language = language or request.event.locale translation.activate(language) request.LANGUAGE_CODE = translation.get_language() with suppress(pytz.UnknownTimeZoneError): if request.user.is_authenticated: tzname = request.user.timezone elif hasattr(request, 'event') and request.event: tzname = request.event.timezone else: tzname = settings.TIME_ZONE timezone.activate(pytz.timezone(tzname)) request.timezone = tzname
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')
def _tzinfome(tzinfo): """Gets a tzinfo object from a string. Args: tzinfo: A string (or string like) object, or a datetime.tzinfo object. Returns: An datetime.tzinfo object. Raises: UnknownTimeZoneError: If the timezone given can't be decoded. """ if not isinstance(tzinfo, datetime.tzinfo): try: tzinfo = pytz.timezone(tzinfo) except AttributeError: raise pytz.UnknownTimeZoneError("Unknown timezone!") return tzinfo # Our "local" timezone
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
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') tz_local = tzlocal.unix._tz_from_env(':' + os.path.join(self.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')
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 as e: logging.error(e) except ImportError as e: logging.error(e) return tz
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)
def _get_localzone(): if winreg is None: raise pytz.UnknownTimeZoneError( 'Runtime support not available') return pytz.timezone(get_localzone_name())
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')
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
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)
def tz(self): """Time zone information.""" try: tz = pytz.timezone(self.timezone) return tz except pytz.UnknownTimeZoneError: raise AstralError('Unknown timezone \'%s\'' % self.timezone)
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!")
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)
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
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
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)
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
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)
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."))