我们从Python开源项目中,提取了以下42个代码示例,用于说明如何使用pytz.common_timezones()。
def _do_execute(self, cmd: Command): if len(cmd.args) != 1: await self.client.send_message( cmd.channel, '{0}: I was unable to parse your timezone because you gave the wrong number of arguments. ' 'See <{1}> for a list of timezones.'.format(cmd.author.mention, self._timezone_loc)) return tz_name = cmd.args[0] if tz_name in pytz.common_timezones: user = await userlib.get_user(discord_id=int(cmd.author.id), register=True) user.set(timezone=tz_name, commit=True) await self.client.send_message( cmd.channel, '{0}: Timezone set as {1}.'.format(cmd.author.mention, tz_name)) else: await self.client.send_message( cmd.channel, '{0}: I was unable to parse your timezone. See <{1}> for a list of timezones.'.format( cmd.author.mention, self._timezone_loc))
def make_cache(self): self.logger.info('start building tzcache ...') # Cache common timezone list dpath = os.path.join( config.RAILGUN_ROOT, 'railgun/website/static/tz' ) if not os.path.isdir(dpath): os.makedirs(dpath, 0755) tzlist = list(common_timezones) # Make each files for l in list_locales(): tz = self.mktz(tzlist, l) tzfile = os.path.join( config.RAILGUN_ROOT, 'railgun/website/static/tz/%s.json' % str(l) ) with open(tzfile, 'wb') as f: f.write(json.dumps(tz)) self.logger.info('tzcache "%s": ok.' % tzfile)
def test_bratislava(self): # Bratislava is the default timezone for Slovakia, but our # heuristics where not adding it to common_timezones. Ideally, # common_timezones should be populated from zone.tab at runtime, # but I'm hesitant to pay the startup cost as loading the list # on demand whilst remaining backwards compatible seems # difficult. self.assertTrue('Europe/Bratislava' in pytz.common_timezones) self.assertTrue('Europe/Bratislava' in pytz.common_timezones_set)
def test_us_eastern(self): self.assertTrue('US/Eastern' in pytz.common_timezones) self.assertTrue('US/Eastern' in pytz.common_timezones_set)
def test_belfast(self): # Belfast uses London time. self.assertTrue('Europe/Belfast' in pytz.all_timezones_set) self.assertFalse('Europe/Belfast' in pytz.common_timezones) self.assertFalse('Europe/Belfast' in pytz.common_timezones_set)
def _sorted_zones(): d = datetime(datetime.today().year, 1, 1) zones = [(tz, pytz.timezone(tz).localize(d).strftime('%z')) for tz in pytz.common_timezones] zones.sort(key=lambda zone: int(zone[1])) return zones
def timezones(): return [(x, x) for x in pytz.common_timezones] + [('', '')]
def gen_tzinfos(): for zone in pytz.common_timezones: try: tzdate = pytz.timezone(zone).localize(dt.utcnow(), is_dst=None) except pytz.NonExistentTimeError: pass else: tzinfo = gettz(zone) if tzinfo: yield tzdate.tzname(), tzinfo
def get_timezone(): search_result_length = 5 search = request.args.get('s', '') search = search.lower() count = 0 timezones_list = [] for tz in common_timezones: if search in tz.lower(): timezones_list.append(append_offset_to_timezone(tz)) count += 1 if count >= search_result_length: break return jsonify({'status': 'OK', 'data': timezones_list})
def get_all_timezones(): data = [append_offset_to_timezone(tz) for tz in common_timezones] return jsonify({'status': 'OK', 'data': data})
def append_offset_to_timezone(tz): """Appends offset value to timezone string: Europe/London -> Europe/London (+000) """ if tz not in common_timezones: return tz offset = datetime.now(timezone(tz)).strftime('%z') return '{0} ({1}:{2})'.format(tz, offset[:3], offset[3:])
def get_timezones(): result = [] for timezone in pytz.common_timezones: result.append((timezone, timezone)) return result
def _get_timezones_as_tuple(): result = [] for timezone in pytz.common_timezones: result.append((timezone, timezone)) return result
def list(self, ctx, area: str = None): """List your current timezone""" bot_channel = self.bot.get_channel(332644650462478336) if bot_channel is None: await ctx.channel.send('The dedicated bot commands channel cannot be found') return False tz_dict = {} for tz in pytz.common_timezones: try: tz_left, tz_right = map(str, tz.split('/')) except Exception: continue if tz_left not in tz_dict: tz_dict[tz_left] = set() tz_dict[tz_left].add(tz_right) tz_areas = list(tz_dict.keys()) tz_areas.sort() if area is None: await bot_channel.send( 'List of available timezone areas : `{}`, {}'.format(', '.join(tz_areas), ctx.author.mention)) else: if area in tz_dict: await bot_channel.send( 'List of available timezones for area **{}** : `{}`, {}'.format(area, ', '.join(sorted(tz_dict[area])), ctx.author.mention)) else: await bot_channel.send('The area **{}** has not been found, {}'.format(area, ctx.author.mention))
def test_timezone_consistency(self): # {{{2 tz_in_settings = [] for continent_data in TIMEZONES: for name_trans in continent_data[1]: tz_in_settings.append(name_trans[0]) tz_in_settings_set = set(tz_in_settings) common_timezones_set = set(pytz.common_timezones) difference1 = tz_in_settings_set.difference(common_timezones_set) assert not difference1, difference1 difference2 = common_timezones_set.difference(tz_in_settings_set) assert not difference2, difference2
def test_cache_keys_are_distinct_for_pytz_vs_dateutil(self): tzs = pytz.common_timezones for tz_name in tzs: if tz_name == 'UTC': # skip utc as it's a special case in dateutil continue tz_p = tslib.maybe_get_tz(tz_name) tz_d = tslib.maybe_get_tz('dateutil/' + tz_name) if tz_d is None: # skip timezones that dateutil doesn't know about. continue self.assertNotEqual(tslib._p_tz_cache_key( tz_p), tslib._p_tz_cache_key(tz_d))
def fields(self, *args, **kwargs): dt = arrow.get(try_parse_date('Mon Jan 22 15:04:05 -0800 2006')).to('utc') choices = ','.join(['{}|{} ({})'.format(f, f, dt.format(f)) for f in PREDEFINED_DATE_FORMATS]) timezones = list(sorted(pytz.common_timezones, key=lambda v: '-' + v if v.startswith('US') else v)) return [ { 'type': 'unicode', 'required': True, 'key': 'to_format', 'choices': choices, 'help_text': 'Provide the format that the date is converted to. For date format help, see: https://zapier.com/help/formatter/#date-time' }, { 'type': 'unicode', 'required': False, 'key': 'to_timezone', 'label': 'To Timezone', 'choices': timezones, 'default': 'UTC', 'help_text': 'Choose a timezone the date should be converted to. (Default: UTC)' }, { 'type': 'unicode', 'required': False, 'key': 'from_format', 'choices': choices, 'help_text': 'If we incorrectly interpret the incoming (input) date, set this to explicitly tell us the format. Otherwise, we will do our best to figure it out.' # NOQA }, { 'type': 'unicode', 'required': False, 'key': 'from_timezone', 'label': 'From Timezone', 'choices': timezones, 'default': 'UTC', 'help_text': 'If no timezone is provided in the incoming (input) data, set this to explicitly tell us which to use. (Default: UTC)' # NOQA }, ]
def get_timezones(): return_value = {} for tz in pytz.common_timezones: c = tz.split("/") if len(c) > 1: if c[0] not in return_value.keys(): return_value[c[0]] = [] return_value[c[0]].append(c[1]) for i in ["GMT"]: if i in return_value.keys(): return_value.pop(i) return return_value
def get_tzlist(): tzlist =list() tzs = pytz.common_timezones for tz in tzs: tzlist.append((tz,tz)) return tzlist
def _get_timezone_choices(): results = [] for tz in pytz.common_timezones: now = datetime.now(pytz.timezone(tz)) offset = now.strftime('%z') results.append((int(offset), tz, '(GMT%s) %s' % (offset, tz))) results.sort() for i in range(len(results)): results[i] = results[i][1:] return results
def clean_timezone(self): timezone = self.cleaned_data['timezone'] if timezone not in common_timezones: timezone = "" return timezone
def user_preference(request): current_user = User.objects.get(username=request.user.username) if request.method == 'POST': if request.POST.get('cancel_button'): messages.warning(request, _(u"Changing user settings canceled")) return HttpResponseRedirect(reverse('home')) else: errors = {} stprofile = StProfile.objects.get_or_create(user=current_user)[0] form_first_name=request.POST.get('first_name', '').strip() current_user.first_name = form_first_name form_last_name=request.POST.get('last_name', '').strip() current_user.last_name = form_last_name form_email=request.POST.get('email', '').strip() users_same_email = User.objects.filter(email=form_email) if len(users_same_email) > 0 and current_user.email != form_email: current_user.email = form_email errors['email'] = _(u"This email address is already in use." + " Please enter a different email address.") elif len(form_email) > 0: try: validate_email(form_email) except ValidationError: errors['email'] = _(u"Enter a valid email address") else: current_user.email = form_email form_language=request.POST.get('lang') if stprofile.language != form_language: stprofile.language = form_language translation.activate(form_language) request.session[translation.LANGUAGE_SESSION_KEY] = form_language form_time_zone=request.POST.get('time_zone') if stprofile.time_zone != form_time_zone: stprofile.time_zone = form_time_zone timezone.activate(form_time_zone) request.session['django_timezone'] = form_time_zone if errors: messages.error(request, _(u'Please, correct the following errors')) return render(request, 'students/user_preference.html', {'current_user': current_user, 'timezones': pytz.common_timezones, 'errors': errors}) current_user.save() stprofile.save() messages.success(request, _(u"User settings changed successfully")) return HttpResponseRedirect(reverse('home')) else: return render(request, 'students/user_preference.html', {'current_user': current_user, 'timezones': pytz.common_timezones})