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')
python类UnknownTimeZoneError()的实例源码
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 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 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 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 _get_localzone():
if winreg is None:
raise pytz.UnknownTimeZoneError(
'Runtime support not available')
return pytz.timezone(get_localzone_name())
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 tz(self):
"""Time zone information."""
try:
tz = pytz.timezone(self.timezone)
return tz
except pytz.UnknownTimeZoneError:
raise AstralError('Unknown timezone \'%s\'' % self.timezone)
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 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 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 _get_localzone():
if winreg is None:
raise pytz.UnknownTimeZoneError(
'Runtime support not available')
return pytz.timezone(get_localzone_name())
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(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 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."))