我们从Python开源项目中,提取了以下42个代码示例,用于说明如何使用pytz.all_timezones()。
def load_setting_export_timezone(logger, config_settings): """ If a user supplied timezone is found in the config settings it will be used to set the dates in the generated audit report, otherwise a local timezone will be used. :param logger: the logger :param config_settings: config settings loaded from config file :return: a timezone from config if valid, else local timezone for this machine """ try: timezone = config_settings['export_options']['timezone'] if timezone is None or timezone not in pytz.all_timezones: timezone = get_localzone() logger.info('No valid timezone found in config file, defaulting to local timezone') return str(timezone) except Exception as ex: log_critical_error(logger, ex, 'Exception parsing timezone from config file') timezone = get_localzone() return str(timezone)
def get_day_based_on_tz(day, tz): """Gets the client date() based on tz passed as parameter. """ server_day = datetime.now(tz=pytz.timezone(SERVER_TIMEZONE)) if tz is not None and tz in pytz.all_timezones: client_day = server_day.astimezone(pytz.timezone(tz)).date() # else not necessary, same day asked = TIMEDELTA_DAYS[day] asked_date = client_day + timedelta(days=asked) if asked_date > server_day.date(): day = 'tomorrow' elif asked_date < server_day.date(): day = 'yesterday' elif asked == -1 and asked_date == server_day.date(): day = 'today' return day
def _detect_timezone_php(): tomatch = (time.tzname[0], time.timezone, time.daylight) now = datetime.datetime.now() matches = [] for tzname in pytz.all_timezones: try: tz = pytz.timezone(tzname) except IOError: continue try: indst = tz.localize(now).timetuple()[-1] if tomatch == (tz._tzname, -tz._utcoffset.seconds, indst): matches.append(tzname) # pylint: disable-msg=W0704 except AttributeError: pass if len(matches) > 1: warnings.warn("We detected multiple matches for the timezone, choosing " "the first %s. (Matches where %s)" % (matches[0], matches)) return pytz.timezone(matches[0])
def test_all_timezones(self): import pytz prev = None for tz in pytz.all_timezones: # just make sure that the timezone conversion utc -> tz works... output = self.transformer.transform('22/01/2016 12:11:10 -05:00', to_format='YYYY-MM-DD HH:mm:ss Z', from_format='MM/DD/YYYY HH:mm:ss', to_timezone=tz) # NOQA self.assertTrue(output.startswith('2016-01-22') or output.startswith('2016-01-23')) if prev: # just make sure that the timezone conversion prev -> tz works... output = self.transformer.transform('22/01/2016 12:11:10', to_format='YYYY-MM-DD HH:mm:ss Z', from_format='MM/DD/YYYY HH:mm:ss', from_timezone=prev, to_timezone=tz) # NOQA self.assertTrue( output.startswith('2016-01-21') or output.startswith('2016-01-22') or output.startswith('2016-01-23')) # just make sure that the timezone conversion tz -> prev works... output = self.transformer.transform('22/01/2016 12:11:10', to_format='YYYY-MM-DD HH:mm:ss Z', from_format='MM/DD/YYYY HH:mm:ss', from_timezone=tz, to_timezone=prev) # NOQA self.assertTrue( output.startswith('2016-01-21') or output.startswith('2016-01-22') or output.startswith('2016-01-23')) prev = tz
def validate_timezone(value): if value not in all_timezones: raise ValidationError( _('%(value)s is not a valid timezone'), params={'value': value}, )
def user_settings(request): polls = Poll.objects.filter(Q(user=request.user) | Q(vote__user=request.user) | Q(group__user=request.user) | Q(pollwatch__user=request.user) ).distinct().order_by('-due_date') if request.method == 'POST': form = BitpollUserSettingsForm(request.POST, instance=request.user) if form.is_valid(): form.save() if request.user.auto_watch: for poll in polls.filter(Q(vote__user=request.user)): try: poll_watch = PollWatch(poll=poll, user=request.user) poll_watch.save() except IntegrityError: pass user_form = BitpollUserSettingsForm(instance=request.user) return TemplateResponse(request, 'base/settings.html', { 'polls': polls, 'user': request.user, 'user_form': user_form, 'languages': USER_LANG, 'timezones': all_timezones, })
def datetimes_in_range(allow_naive=None, timezones=None, start_date=None, end_date=None, start_inclusive=True, end_inclusive=True): """Return a strategy for generating datetimes. allow_naive=True will cause the values to sometimes be naive. timezones is the set of permissible timezones. If set to an empty collection all timezones must be naive. If set to None all available timezones will be used. """ if timezones is None: timezones = list(pytz.all_timezones) timezones.remove(u'UTC') timezones.insert(0, u'UTC') timezones = [ tz if isinstance(tz, dt.tzinfo) else pytz.timezone(tz) for tz in timezones ] if allow_naive is None: allow_naive = not timezones if not (timezones or allow_naive): raise InvalidArgument( u'Cannot create non-naive datetimes with no timezones allowed' ) return DatetimeStrategy( allow_naive=allow_naive, timezones=timezones, start_date=start_date, end_date=end_date, start_inclusive=start_inclusive, end_inclusive=end_inclusive )
def testRoundtrip(self): dt = datetime(2004, 2, 1, 0, 0, 0) for zone in pytz.all_timezones: tz = pytz.timezone(zone) self._roundtrip_tzinfo(tz)
def allTimeZones(self): for tz in all_timezones: self.oop.scr.insert(tk.INSERT, tz + '\n') # TZ Local Button callback
def allTimeZones(self): for tz in all_timezones: self.scr.insert(tk.INSERT, tz + '\n') # TZ Local Button callback
def __init__(self, context=None, logger=None): """ Initializes the instance :param context: Lambda context :param logger: Optional logger for warnings, if None then warnings are printed to console """ self._logger = logger self._this_account = None self._context = context self._all_timezones = {tz.lower(): tz for tz in pytz.all_timezones} self._all_actions = actions.all_actions() self._s3_client = None self._s3_configured_cross_account_roles = None
def tz_arg(timezone: str): """ Get timezone from a string. """ for tz in all_timezones: if tz.lower().endswith(timezone.lower()): return tz return None
def _tz_get(self): return [(x, x) for x in pytz.all_timezones]
def _list_tz(self,cr,uid, context=None): # put POSIX 'Etc/*' entries at the end to avoid confusing users - see bug 1086728 return [(tz,tz) for tz in sorted(pytz.all_timezones, key=lambda tz: tz if not tz.startswith('Etc/') else '_')]
def timezone(self): """The name of the time zone for the location. A list of time zone names can be obtained from pytz. For example. >>> from pytz import all_timezones >>> for timezone in all_timezones: ... print(timezone) """ if self._timezone_location != '': return '%s/%s' % (self._timezone_group, self._timezone_location) else: return self._timezone_group
def timezone(self, name): if name not in pytz.all_timezones: raise ValueError('Timezone \'%s\' not recognized' % name) try: self._timezone_group, self._timezone_location = \ name.split('/', 1) except ValueError: self._timezone_group = name self._timezone_location = ''
def validate_timezone(zone): """Return an IETF timezone from the given IETF zone or common abbreviation. If the length of the zone is 4 or less, it will be upper-cased before being looked up; otherwise it will be title-cased. This is the expected case-insensitivity behavior in the majority of cases. For example, ``'edt'`` and ``'america/new_york'`` will both return ``'America/New_York'``. If the zone is not valid, ``ValueError`` will be raised. If ``pytz`` is not available, and the given zone is anything other than ``'UTC'``, ``ValueError`` will be raised. """ if zone is None: return None if not pytz: if zone.upper() != 'UTC': raise ValueError('Only UTC available, since pytz is not installed.') else: return zone zone = '/'.join(reversed(zone.split(', '))).replace(' ', '_') if len(zone) <= 4: zone = zone.upper() else: zone = zone.title() if zone in pytz.all_timezones: return zone else: raise ValueError("Invalid time zone.")
def local_timezone(self): """Returns the name of the local timezone, for informational purposes.""" if self._local_tz.zone in pytz.all_timezones: return self._local_tz.zone return self.timezone
def timezone(tz): if tz not in pytz.all_timezones: raise ValidationError('Invalid/unknown timezone ' + tz)
def get(self): """gets all known timezones""" return { API_ENVELOPE: map(lambda timezone: {"name": timezone}, pytz.all_timezones) }
def handle(self, arguments, user, **kwargs): tz = user.preferences['global__timezone'] if arguments: if arguments not in pytz.all_timezones: raise HandleError('Invalid timezone', code='invalid_arg') tz = arguments return { 'current': timezone.now(), 'timezone': tz, }
def _tz_get(self): # put POSIX 'Etc/*' entries at the end to avoid confusing users - see bug 1086728 return [(tz,tz) for tz in sorted(pytz.all_timezones, key=lambda tz: tz if not tz.startswith('Etc/') else '_')]
def create_list(): tz_list = [] for tz in pytz.all_timezones: tz_list.append(tz) return tz_list
def test_pytz_timezone_serializing(self): """ Serializing with timezones from pytz test """ try: import pytz except ImportError: return self.skipTest("pytz not installed") # NOQA # Avoid conflicting cached tzinfo from other tests def unregister_tzid(tzid): """Clear tzid from icalendar TZID registry""" if icalendar.getTzid(tzid, False): icalendar.registerTzid(tzid, None) unregister_tzid('US/Eastern') eastern = pytz.timezone('US/Eastern') cal = base.Component('VCALENDAR') cal.setBehavior(icalendar.VCalendar2_0) ev = cal.add('vevent') ev.add('dtstart').value = eastern.localize( datetime.datetime(2008, 10, 12, 9)) serialized = cal.serialize() expected_vtimezone = get_test_file("tz_us_eastern.ics") self.assertIn( expected_vtimezone.replace('\r\n', '\n'), serialized.replace('\r\n', '\n') ) # Exhaustively test all zones (just looking for no errors) for tzname in pytz.all_timezones: unregister_tzid(tzname) tz = icalendar.TimezoneComponent(tzinfo=pytz.timezone(tzname)) tz.serialize()
def ask_timezone(question, default, tzurl): """Prompt for time zone and validate input""" lower_tz = [tz.lower() for tz in pytz.all_timezones] while True: r = ask(question, str_compat, default) r = r.strip().replace(' ', '_').lower() if r in lower_tz: r = pytz.all_timezones[lower_tz.index(r)] break else: print('Please enter a valid time zone:\n' ' (check [{0}])'.format(tzurl)) return r
def test_timezone_search_complete_name(self): for w in pytz.all_timezones: h = kron.timezone.search(w) self.assertEqual(h, w)
def test_timezone_search_lower_complete_name(self): for w in pytz.all_timezones: h = kron.timezone.search(w.lower()) self.assertEqual(h, w)
def test_timezone_search_all(self): h = kron.timezone.search('') w = pytz.all_timezones self.assertEqual(h, w)
def test_cli_search_timezone(self): h = kron.cli(['-s', '']) w = '\n'.join(pytz.all_timezones) self.assertEqual(h, w)
def search(cls, name=None): """Resolve timezone given a name ``name`` can be: * omitted or None: returns name of the local timezone via tzlocal or UTC * string matching a timezone name in ``pytz.all_timezones``: returns the timezone name in proper case * empty string ('') or wildcard regular expression ('.*'): returns a list with all timezone names * any other string: used as a regular expression; multiple or zero matches returns a list with the matched timezone names """ if name == None: try: return tzlocal.get_localzone().zone except: return 'UTC' if name in pytz.all_timezones: return name name_ = name.lower() matches = [] for t in pytz.all_timezones: t_ = t.lower() if name_ == t_: return t if re.search(name, t) or re.search(name_, t_): matches.append(t) if len(matches) == 1: return matches[0] else: return matches # Error classes
def _detect_timezone_etc_localtime(): matches = [] if os.path.exists("/etc/localtime"): localtime = pytz.tzfile.build_tzinfo("/etc/localtime", file("/etc/localtime")) # See if we can find a "Human Name" for this.. for tzname in pytz.all_timezones: tz = _tzinfome(tzname) if dir(tz) != dir(localtime): continue for attrib in dir(tz): # Ignore functions and specials if callable(getattr(tz, attrib)) or attrib.startswith("__"): continue # This will always be different if attrib == "zone" or attrib == "_tzinfos": continue if getattr(tz, attrib) != getattr(localtime, attrib): break # We get here iff break didn't happen, i.e. no meaningful attributes # differ between tz and localtime else: matches.append(tzname) #if len(matches) == 1: # return _tzinfome(matches[0]) #else: # # Warn the person about this! # warning = "Could not get a human name for your timezone: " # if len(matches) > 1: # warning += ("We detected multiple matches for your /etc/localtime. " # "(Matches where %s)" % matches) # else: # warning += "We detected no matches for your /etc/localtime." # warnings.warn(warning) # # return localtime if len(matches) > 0: return _tzinfome(matches[0])
def get_subscribers(self, targetings, hours_whitelist, volume): logger.info("SubscriberService.get_subscribers: getting subscribers") start_time = time.time() timezones = [tz for tz in pytz.all_timezones if (datetime .now(pytz.timezone(tz)).hour in hours_whitelist)] targetings.append({ "field": "unsub", "operator": "NOT IN", "values": [1, "true"] }) if timezones: targetings.append({ "field": "timezone", "operator": "IN", "values": timezones }) s = Search(using=es, index="users") operator_mappings = { 'IN': 'must', 'NOT IN': 'must_not', } q = Q() for condition in targetings: condition_pair = {condition["field"]: condition["values"]} terms_q = Q('terms', **condition_pair) bool_operator = operator_mappings[condition['operator']] bool_q = Q('bool', **{bool_operator: terms_q}) q += bool_q s = s.query(q) s.query = dslq.FunctionScore( query=s.query, functions=[dslq.SF('random_score')], boost_mode="replace" ) s = s[:volume] try: res = s.execute() except Exception as e: logger.error(f"SubscriberService.get_subscribers: Exception {e}") else: subscribers = [] for row in res.hits: subscriber = row.to_dict() subscriber['_id'] = row.meta.id subscribers.append(subscriber) end_time = time.time() logger.debug(f"SubscriberService.get_subscribers: finished in " f"{int((end_time - start_time) * 1000)}ms") return subscribers
def edit_preferences(userid, timezone=None, preferences=None, jsonb_settings=None): """ Apply changes to stored preferences for a given user. :param userid: The userid to apply changes to :param timezone: (optional) new Timezone to set for user :param preferences: (optional) old-style char preferences, overwrites all previous settings :param jsonb_settings: (optional) JSON preferences, overwrites all previous settings :return: None """ config = d.get_config(userid) tooyoung = False if preferences is not None: tooyoung |= get_user_age(userid) < preferences.rating.minimum_age if jsonb_settings is not None: sfwrating = jsonb_settings.max_sfw_rating sfwrating = ratings.CODE_MAP.get(sfwrating, ratings.GENERAL) tooyoung |= get_user_age(userid) < sfwrating.minimum_age if tooyoung: raise WeasylError("birthdayInsufficient") if timezone is not None and timezone not in pytz.all_timezones: raise WeasylError('invalidTimezone') db = d.connect() updates = {} if preferences is not None: # update legacy preferences # clear out the option codes that are being replaced. for i in Config.all_option_codes: config = config.replace(i, "") config_str = config + preferences.to_code() updates['config'] = config_str d._get_config.invalidate(userid) if jsonb_settings is not None: # update jsonb preferences updates['jsonb_settings'] = jsonb_settings.get_raw() d._get_profile_settings.invalidate(userid) d.engine.execute( tables.profile.update().where(tables.profile.c.userid == userid), updates ) # update TZ if timezone is not None: tz = db.query(orm.UserTimezone).get(userid) if tz is None: tz = orm.UserTimezone(userid=userid) db.add(tz) tz.timezone = timezone db.flush() tz.cache() else: db.flush()