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))
python类common_timezones()的实例源码
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 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 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_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 timezones():
return [(x, x) for x in pytz.common_timezones] + [('', '')]
def timezones():
return [(x, x) for x in pytz.common_timezones] + [('', '')]
test_timezones.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
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 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 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)