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)
python类all_timezones()的实例源码
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)
Callbacks_Refactored.py 文件源码
项目:Python-GUI-Programming-Cookbook-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def allTimeZones(self):
for tz in all_timezones:
self.oop.scr.insert(tk.INSERT, tz + '\n')
# TZ Local Button callback
GUI.py 文件源码
项目:Python-GUI-Programming-Cookbook-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 27
收藏 0
点赞 0
评论 0
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 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 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 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 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 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 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 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 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 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 create_list():
tz_list = []
for tz in pytz.all_timezones:
tz_list.append(tz)
return tz_list