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
python类UnknownTimeZoneError()的实例源码
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 _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 _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 _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 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 _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 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 _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 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 _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 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 _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 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 _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 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 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 _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 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 _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 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())