How to use the pytz.UnknownTimeZoneError function in pytz

To help you get started, we’ve selected a few pytz examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github google / grr / parsers / linux_log_parser.py View on Github external
logging.debug('[LogParser] Tool run with debug turned ON.')

  if not options.filename:
    logging.error('[LogParser] Not correctly run (missing file?)')
    sys.exit(1)

  try:
    handle = SmartOpenFile(options.filename)
  except OpenFileError as err:
    logging.error('[LogParser] Unable to open file %s: %s',
                  options.filename, err)
    sys.exit(2)

  try:
    time_zone = pytz.timezone(options.tzone)
  except pytz.UnknownTimeZoneError:
    logging.error(('[LogParser] Time zone was not properly verified,'
                   ' exiting. Please use a valid timezone (%s not'
                   ' valid). Use "-z list" to get a list of all'
                   'available options.'), options.tzone)
    sys.exit(1)
  logging.debug('[LogParser] Time ZONE used (verified) [%s]', time_zone)

  logging.debug(('[LogParser] File (%s) exists and has been '
                 'opened for parsing.'), options.filename)
  ExtractTimestamps(handle, time_zone, output_formatter, out_handle)
  handle.close()
github pkittenis / cronify / cronify / cronify.py View on Github external
def _check_timezone_info(self, watch_data):
        """Check if we have timezone configuration in watch data, parse if needed"""
        if not 'file_tz' in watch_data and not 'local_tz' in watch_data:
            return
        for tz_key in ['file_tz', 'local_tz']:
            if tz_key in watch_data:
                try:
                    watch_data[tz_key] = pytz.timezone(watch_data[tz_key])
                except pytz.UnknownTimeZoneError:
                    logger.error("Invalid timezone %s given as '%s' configuration, cannot continue",
                                 watch_data[tz_key], tz_key,)
                    sys.exit(1)
                else:
                    logger.debug("Got timezone configuration for %s = %s", tz_key, watch_data[tz_key],)
github Southpaw-TACTIC / TACTIC / 3rd_party / common / site-packages / tzlocal_olson / win32.py View on Github external
tzkey.Close()
        handle.Close()

    if tzkeyname is None:
        raise LookupError('Can not find Windows timezone configuration')

    timezone = win_tz.get(tzkeyname)
    if timezone is None:
        # Nope, that didn't work. Try adding "Standard Time",
        # it seems to work a lot of times:
        timezone = win_tz.get(tzkeyname + " Standard Time")

    # Return what we have.
    if timezone is None:
        raise pytz.UnknownTimeZoneError('Can not find timezone ' + tzkeyname)

    return timezone
github AwesomeFoodCoops / odoo-production / odoo / addons / website / models / ir_http.py View on Github external
path.insert(1, request.lang)
                    path = '/'.join(path) or '/'
                    redirect = request.redirect(path + '?' + request.httprequest.query_string)
                    redirect.set_cookie('website_lang', request.lang)
                    return redirect
                elif url_lang:
                    request.uid = None
                    path.pop(1)
                    return self.reroute('/'.join(path) or '/')
            if request.lang == request.website.default_lang_code:
                request.context['edit_translations'] = False
            if not request.context.get('tz'):
                request.context['tz'] = request.session.get('geoip', {}).get('time_zone')
                try:
                    pytz.timezone(request.context['tz'] or '')
                except pytz.UnknownTimeZoneError:
                    request.context.pop('tz')

            # bind modified context
            request.website = request.website.with_context(request.context)

        # cache for auth public
        cache_time = getattr(func, 'routing', {}).get('cache')
        cache_enable = cache_time and request.httprequest.method == "GET" and request.website.user_id.id == request.uid
        cache_response = None
        if cache_enable:
            key = self.get_page_key()
            try:
                r = self.pool.cache[key]
                if r['time'] + cache_time > time.time():
                    cache_response = openerp.http.Response(r['content'], mimetype=r['mimetype'])
                else:
github O365 / python-o365 / O365 / utils / windows_tz.py View on Github external
def get_windows_tz(iana_tz):
    """ Returns a valid windows TimeZone from a given pytz TimeZone
    (Iana/Olson Timezones)
    Note: Windows Timezones are SHIT!... no ... really THEY ARE
    HOLY FUCKING SHIT!.
    """
    timezone = IANA_TO_WIN.get(
        iana_tz.zone if isinstance(iana_tz, tzinfo) else iana_tz)
    if timezone is None:
        raise pytz.UnknownTimeZoneError(
            "Can't find Iana TimeZone " + iana_tz.zone)

    return timezone
github pretalx / pretalx / src / pretalx / common / middleware / event.py View on Github external
request.event.locales
            if (hasattr(request, "event") and request.event)
            else settings.LANGUAGE_CODES
        )
        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 hasattr(request, "event") and request.event:
                tzname = request.event.timezone
            elif request.user.is_authenticated:
                tzname = request.user.timezone
            else:
                tzname = settings.TIME_ZONE
            timezone.activate(pytz.timezone(tzname))
            request.timezone = tzname
github backtrader / backtrader / backtrader / utils / dateintern.py View on Github external
tzstr = isinstance(tz, string_types)
    if tz is None or not tzstr:
        return Localizer(tz)

    try:
        import pytz  # keep the import very local
    except ImportError:
        return Localizer(tz)    # nothing can be done

    tzs = tz
    if tzs == 'CST':  # usual alias
        tzs = 'CST6CDT'

    try:
        tz = pytz.timezone(tzs)
    except pytz.UnknownTimeZoneError:
        return Localizer(tz)    # nothing can be done

    return tz
github pimutils / khal / khal / settings / utils.py View on Github external
def is_timezone(tzstring):
    """tries to convert tzstring into a pytz timezone

    raises a VdtvalueError if tzstring is not valid
    """
    if not tzstring:
        return get_localzone()
    try:
        return pytz.timezone(tzstring)
    except pytz.UnknownTimeZoneError:
        raise VdtValueError("Unknown timezone {}".format(tzstring))
github indico / indico / indico / web / http_api / hooks / base.py View on Github external
def _getParams(self):
        self._offset = get_query_parameter(self._queryParams, ['O', 'offset'], 0, integer=True)
        if self._offset < 0:
            raise HTTPAPIError('Offset must be a positive number', 400)
        self._orderBy = get_query_parameter(self._queryParams, ['o', 'order'])
        self._descending = get_query_parameter(self._queryParams, ['c', 'descending'], 'no') == 'yes'
        self._detail = get_query_parameter(self._queryParams, ['d', 'detail'], self.DEFAULT_DETAIL)
        tzName = get_query_parameter(self._queryParams, ['tz'], None)

        if tzName is None:
            tzName = config.DEFAULT_TIMEZONE
        try:
            self._tz = pytz.timezone(tzName)
        except pytz.UnknownTimeZoneError as e:
            raise HTTPAPIError("Bad timezone: '%s'" % e.message, 400)
        max = self.MAX_RECORDS.get(self._detail, 1000)
        self._userLimit = get_query_parameter(self._queryParams, ['n', 'limit'], 0, integer=True)
        if self._userLimit > max:
            raise HTTPAPIError("You can only request up to %d records per request with the detail level '%s'" %
                               (max, self._detail), 400)
        self._limit = self._userLimit if self._userLimit > 0 else max

        fromDT = get_query_parameter(self._queryParams, ['f', 'from'])
        toDT = get_query_parameter(self._queryParams, ['t', 'to'])
        dayDT = get_query_parameter(self._queryParams, ['day'])

        if (fromDT or toDT) and dayDT:
            raise HTTPAPIError("'day' can only be used without 'from' and 'to'", 400)
        elif dayDT:
            fromDT = toDT = dayDT