def create_list():
tz_list = []
for tz in pytz.all_timezones:
tz_list.append(tz)
return tz_list
python类all_timezones()的实例源码
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 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()