本文整理汇总了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)
示例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
示例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")
示例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)
示例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')
示例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
示例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)
示例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
示例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
示例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)
示例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")
示例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)
示例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'
)
示例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())
示例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)