Python pytz.UnknownTimeZoneError() Examples

The following are 30 code examples of pytz.UnknownTimeZoneError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pytz , or try the search function .
Example #1
Source File: base.py    From darksky with MIT License 7 votes vote down vote up
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) 
Example #2
Source File: __init__.py    From dateparser with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #3
Source File: timefmt.py    From volatility with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #4
Source File: poll.py    From pollmaster with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: timefmt.py    From vortessence with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #6
Source File: utils.py    From opentaps_seas with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 
Example #7
Source File: unix.py    From xbmc-addons-chinese with GNU General Public License v2.0 6 votes vote down vote up
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") 
Example #8
Source File: tests.py    From xbmc-addons-chinese with GNU General Public License v2.0 6 votes vote down vote up
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') 
Example #9
Source File: unix.py    From plugin.video.iptv.recorder with GNU General Public License v3.0 6 votes vote down vote up
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") 
Example #10
Source File: unix.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
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") 
Example #11
Source File: dates.py    From pySINDy with MIT License 6 votes vote down vote up
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) 
Example #12
Source File: _unix.py    From pySINDy with MIT License 6 votes vote down vote up
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") 
Example #13
Source File: timefmt.py    From DAMM with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #14
Source File: unix.py    From komodo-wakatime with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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") 
Example #15
Source File: dates.py    From sndlatr with Apache License 2.0 6 votes vote down vote up
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) 
Example #16
Source File: _unix.py    From sndlatr with Apache License 2.0 6 votes vote down vote up
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") 
Example #17
Source File: timefmt.py    From volatility with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #18
Source File: timefmt.py    From aumfor with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #19
Source File: unix.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
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") 
Example #20
Source File: fields.py    From django-timezone-utils with MIT License 6 votes vote down vote up
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 
Example #21
Source File: fields.py    From django-timezone-utils with MIT License 6 votes vote down vote up
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 
Example #22
Source File: test_utils.py    From dateparser with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_localize_timezone_function_raise_error(self, date, timezone):
        self.assertRaises(UnknownTimeZoneError, localize_timezone, date, timezone) 
Example #23
Source File: forms.py    From django-timezone-utils with MIT License 5 votes vote down vote up
def to_python(self, value):
        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}
            ) 
Example #24
Source File: test_invalid_tzdatetimefield.py    From django-timezone-utils with MIT License 5 votes vote down vote up
def test_bad_populate_from_timezone_as_charfield(self):
        with self.assertRaises(pytz.UnknownTimeZoneError):
            ModelWithBadTimeZoneCharField.objects.create() 
Example #25
Source File: croninfo.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
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 
Example #26
Source File: jobs.py    From rasa-for-botfront with Apache License 2.0 5 votes vote down vote up
def scheduler() -> AsyncIOScheduler:
    """Thread global scheduler to handle all recurring tasks.

    If no scheduler exists yet, this will instantiate one."""

    global __scheduler

    if not __scheduler:
        try:
            __scheduler = AsyncIOScheduler(event_loop=asyncio.get_event_loop())
            __scheduler.start()
            return __scheduler
        except UnknownTimeZoneError:
            raise_warning(
                "apscheduler could not find a timezone and is "
                "defaulting to utc. This is probably because "
                "your system timezone is not set. "
                'Set it with e.g. echo "Europe/Berlin" > '
                "/etc/timezone"
            )
            __scheduler = AsyncIOScheduler(
                event_loop=asyncio.get_event_loop(), timezone=utc
            )
            __scheduler.start()
            return __scheduler
    else:
        # scheduler already created, make sure it is running on
        # the correct loop
        # noinspection PyProtectedMember
        if not __scheduler._eventloop == asyncio.get_event_loop():
            raise RuntimeError(
                "Detected inconsistent loop usage. "
                "Trying to schedule a task on a new event "
                "loop, but scheduler was created with a "
                "different event loop. Make sure there "
                "is only one event loop in use and that the "
                "scheduler is running on that one."
            )
        return __scheduler 
Example #27
Source File: unix.py    From plugin.video.iptv.recorder with GNU General Public License v3.0 5 votes vote down vote up
def _try_tz_from_env():
    tzenv = os.environ.get('TZ')
    if tzenv:
        try:
            return _tz_from_env(tzenv)
        except pytz.UnknownTimeZoneError:
            pass 
Example #28
Source File: tests.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_timezone_templatetag_invalid_argument(self):
        with self.assertRaises(TemplateSyntaxError):
            Template("{% load tz %}{% timezone %}{% endtimezone %}").render()
        with self.assertRaises(pytz.UnknownTimeZoneError):
            Template("{% load tz %}{% timezone tz %}{% endtimezone %}").render(Context({'tz': 'foobar'})) 
Example #29
Source File: __init__.py    From Flask-MonitoringDashboard with MIT License 5 votes vote down vote up
def __init__(self):
        """
            Sets the default values for the project
        """
        # dashboard
        self.version = '1.0'
        self.link = 'dashboard'
        self.monitor_level = 1
        self.outlier_detection_constant = 2.5
        self.sampling_period = 5 / 1000.0
        self.enable_logging = False

        # database
        self.database_name = 'sqlite:///flask_monitoringdashboard.db'
        self.table_prefix = ''

        # authentication
        self.username = 'admin'
        self.password = 'admin'
        self.guest_username = ['guest']
        self.guest_password = ['guest_password']
        self.security_token = 'cc83733cb0af8b884ff6577086b87909'

        # visualization
        self.colors = {}
        try:
            self.timezone = pytz.timezone(str(get_localzone()))
        except pytz.UnknownTimeZoneError:
            log('Using default timezone, which is UTC')
            self.timezone = pytz.timezone('UTC')

        # define a custom function to retrieve the session_id or username
        self.group_by = None

        # store the Flask app
        self.app = None 
Example #30
Source File: test_preprocess.py    From catalyst with Apache License 2.0 5 votes vote down vote up
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)