本文整理汇总了Python中time.tzset方法的典型用法代码示例。如果您正苦于以下问题:Python time.tzset方法的具体用法?Python time.tzset怎么用?Python time.tzset使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类time
的用法示例。
在下文中一共展示了time.tzset方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testSyncClockToNtp
# 需要导入模块: import time [as 别名]
# 或者: from time import tzset [as 别名]
def testSyncClockToNtp(self, request, subproc, sleep):
os.environ['TZ'] = 'UTC'
time.tzset()
return_time = mock.Mock()
return_time.ref_time = 1453220630.64458
request.side_effect = iter([None, None, None, return_time])
subproc.return_value = True
# Too Few Retries
self.assertRaises(ntp.NtpException, ntp.SyncClockToNtp)
sleep.assert_has_calls([mock.call(30), mock.call(30)])
# Sufficient Retries
ntp.SyncClockToNtp(retries=3, server='time.google.com')
request.assert_called_with(mock.ANY, 'time.google.com', version=3)
subproc.assert_has_calls([
mock.call(
r'X:\Windows\System32\cmd.exe /c date 01-19-2016', shell=True),
mock.call(r'X:\Windows\System32\cmd.exe /c time 16:23:50', shell=True)
])
# Socket Error
request.side_effect = ntp.socket.gaierror
self.assertRaises(ntp.NtpException, ntp.SyncClockToNtp)
# NTP lib error
request.side_effect = ntp.ntplib.NTPException
self.assertRaises(ntp.NtpException, ntp.SyncClockToNtp)
示例2: main
# 需要导入模块: import time [as 别名]
# 或者: from time import tzset [as 别名]
def main():
shutdown.install_signal_handlers()
# The timezone must be set in the devappserver2 process rather than just in
# the runtime so printed log timestamps are consistent and the taskqueue stub
# expects the timezone to be UTC. The runtime inherits the environment.
os.environ['TZ'] = 'UTC'
if hasattr(time, 'tzset'):
# time.tzet() should be called on Unix, but doesn't exist on Windows.
time.tzset()
options = PARSER.parse_args()
dev_server = DevelopmentServer()
try:
dev_server.start(options)
shutdown.wait_until_shutdown()
finally:
dev_server.stop()
示例3: __calc_timezone
# 需要导入模块: import time [as 别名]
# 或者: from time import tzset [as 别名]
def __calc_timezone(self):
# Set self.timezone by using time.tzname.
# Do not worry about possibility of time.tzname[0] == time.tzname[1]
# and time.daylight; handle that in strptime.
try:
time.tzset()
except AttributeError:
pass
self.tzname = time.tzname
self.daylight = time.daylight
no_saving = frozenset(["utc", "gmt", self.tzname[0].lower()])
if self.daylight:
has_saving = frozenset([self.tzname[1].lower()])
else:
has_saving = frozenset()
self.timezone = (no_saving, has_saving)
示例4: test_bad_timezone
# 需要导入模块: import time [as 别名]
# 或者: from time import tzset [as 别名]
def test_bad_timezone(self):
# Explicitly test possibility of bad timezone;
# when time.tzname[0] == time.tzname[1] and time.daylight
tz_name = time.tzname[0]
if tz_name.upper() in ("UTC", "GMT"):
self.skipTest('need non-UTC/GMT timezone')
with support.swap_attr(time, 'tzname', (tz_name, tz_name)), \
support.swap_attr(time, 'daylight', 1), \
support.swap_attr(time, 'tzset', lambda: None):
time.tzname = (tz_name, tz_name)
time.daylight = 1
tz_value = _strptime._strptime_time(tz_name, "%Z")[8]
self.assertEqual(tz_value, -1,
"%s lead to a timezone value of %s instead of -1 when "
"time.daylight set to %s and passing in %s" %
(time.tzname, tz_value, time.daylight, tz_name))
示例5: test_TimeRE_recreation_timezone
# 需要导入模块: import time [as 别名]
# 或者: from time import tzset [as 别名]
def test_TimeRE_recreation_timezone(self):
# The TimeRE instance should be recreated upon changing the timezone.
oldtzname = time.tzname
tm = _strptime._strptime_time(time.tzname[0], '%Z')
self.assertEqual(tm.tm_isdst, 0)
tm = _strptime._strptime_time(time.tzname[1], '%Z')
self.assertEqual(tm.tm_isdst, 1)
# Get id of current cache object.
first_time_re = _strptime._TimeRE_cache
# Change the timezone and force a recreation of the cache.
os.environ['TZ'] = 'EST+05EDT,M3.2.0,M11.1.0'
time.tzset()
tm = _strptime._strptime_time(time.tzname[0], '%Z')
self.assertEqual(tm.tm_isdst, 0)
tm = _strptime._strptime_time(time.tzname[1], '%Z')
self.assertEqual(tm.tm_isdst, 1)
# Get the new cache object's id.
second_time_re = _strptime._TimeRE_cache
# They should not be equal.
self.assertIsNot(first_time_re, second_time_re)
# Make sure old names no longer accepted.
with self.assertRaises(ValueError):
_strptime._strptime_time(oldtzname[0], '%Z')
with self.assertRaises(ValueError):
_strptime._strptime_time(oldtzname[1], '%Z')
示例6: display_datetime
# 需要导入模块: import time [as 别名]
# 或者: from time import tzset [as 别名]
def display_datetime(dt, custom_tz = None):
"""Returns a string from a datetime according to the display TZ (or a custom one"""
timeformat = "%Y-%m-%d %H:%M:%S %Z%z"
if dt.tzinfo is not None and dt.tzinfo.utcoffset(dt) is not None:
if custom_tz is not None:
dt = dt.astimezone(custom_tz)
elif config.TZ is not None:
if isinstance(config.TZ, str):
secs = calendar.timegm(dt.timetuple())
os.environ['TZ'] = config.TZ
time.tzset()
# Remove the %z which appears not to work
timeformat = timeformat[:-2]
return time.strftime(timeformat, time.localtime(secs))
else:
dt = dt.astimezone(config.tz)
return ("{0:" + timeformat + "}").format(dt)
示例7: tz_from_string
# 需要导入模块: import time [as 别名]
# 或者: from time import tzset [as 别名]
def tz_from_string(_option, _opt_str, value, parser):
"""Stores a tzinfo object from a string"""
if value is not None:
if value[0] in ['+', '-']:
# Handed a numeric offset, create an OffsetTzInfo
valarray = [value[i:i + 2] for i in range(1, len(value), 2)]
multipliers = [3600, 60]
offset = 0
for i in range(min(len(valarray), len(multipliers))):
offset += int(valarray[i]) * multipliers[i]
if value[0] == '-':
offset = -offset
timezone = OffsetTzInfo(offset = offset)
else:
# Value is a lookup, choose pytz over time.tzset
if tz_pytz:
try:
timezone = pytz.timezone(value)
except pytz.UnknownTimeZoneError:
debug.error("Unknown display timezone specified")
else:
if not hasattr(time, 'tzset'):
debug.error("This operating system doesn't support tzset, please either specify an offset (eg. +1000) or install pytz")
timezone = value
parser.values.tz = timezone
示例8: update_connections_time_zone
# 需要导入模块: import time [as 别名]
# 或者: from time import tzset [as 别名]
def update_connections_time_zone(**kwargs):
if kwargs['setting'] == 'TIME_ZONE':
# Reset process time zone
if hasattr(time, 'tzset'):
if kwargs['value']:
os.environ['TZ'] = kwargs['value']
else:
os.environ.pop('TZ', None)
time.tzset()
# Reset local time zone cache
timezone.get_default_timezone.cache_clear()
# Reset the database connections' time zone
if kwargs['setting'] in {'TIME_ZONE', 'USE_TZ'}:
for conn in connections.all():
try:
del conn.timezone
except AttributeError:
pass
try:
del conn.timezone_name
except AttributeError:
pass
conn.ensure_timezone()
示例9: setTZ
# 需要导入模块: import time [as 别名]
# 或者: from time import tzset [as 别名]
def setTZ(name):
"""
Set time zone.
@param name: a time zone name
@type name: L{str}
"""
if tzset is None:
return
if name is None:
try:
del environ["TZ"]
except KeyError:
pass
else:
environ["TZ"] = name
tzset()
示例10: setUp
# 需要导入模块: import time [as 别名]
# 或者: from time import tzset [as 别名]
def setUp(self):
"""
Patch the L{ls} module's time function so the results of L{lsLine} are
deterministic.
"""
self.now = 123456789
def fakeTime():
return self.now
self.patch(ls, 'time', fakeTime)
# Make sure that the timezone ends up the same after these tests as
# it was before.
if 'TZ' in os.environ:
self.addCleanup(operator.setitem, os.environ, 'TZ', os.environ['TZ'])
self.addCleanup(time.tzset)
else:
def cleanup():
# os.environ.pop is broken! Don't use it! Ever! Or die!
try:
del os.environ['TZ']
except KeyError:
pass
time.tzset()
self.addCleanup(cleanup)
示例11: test_formatTimeDefault
# 需要导入模块: import time [as 别名]
# 或者: from time import tzset [as 别名]
def test_formatTimeDefault(self):
"""
Time is first field. Default time stamp format is RFC 3339 and offset
respects the timezone as set by the standard C{TZ} environment variable
and L{tzset} API.
"""
if tzset is None:
raise SkipTest(
"Platform cannot change timezone; unable to verify offsets."
)
addTZCleanup(self)
setTZ("UTC+00")
t = mktime((2013, 9, 24, 11, 40, 47, 1, 267, 1))
event = dict(log_format=u"XYZZY", log_time=t)
self.assertEqual(
formatEventAsClassicLogText(event),
u"2013-09-24T11:40:47+0000 [-#-] XYZZY\n",
)
示例12: __calc_timezone
# 需要导入模块: import time [as 别名]
# 或者: from time import tzset [as 别名]
def __calc_timezone(self):
# Set self.timezone by using time.tzname.
# Do not worry about possibility of time.tzname[0] == time.tzname[1]
# and time.daylight; handle that in strptime.
try:
time.tzset()
except AttributeError:
pass
self.tzname = time.tzname
self.daylight = time.daylight
no_saving = frozenset({"utc", "gmt", self.tzname[0].lower()})
if self.daylight:
has_saving = frozenset({self.tzname[1].lower()})
else:
has_saving = frozenset()
self.timezone = (no_saving, has_saving)
示例13: test_formatTimeDefault
# 需要导入模块: import time [as 别名]
# 或者: from time import tzset [as 别名]
def test_formatTimeDefault(self):
"""
Time is first field. Default time stamp format is RFC 3339 and offset
respects the timezone as set by the standard C{TZ} environment variable
and L{tzset} API.
"""
if tzset is None:
raise SkipTest(
"Platform cannot change timezone; unable to verify offsets."
)
addTZCleanup(self)
setTZ("UTC+00")
t = mktime((2013, 9, 24, 11, 40, 47, 1, 267, 1))
event = dict(log_format=u"XYZZY", log_time=t)
self.assertEqual(
formatEventAsClassicLogText(event),
u"2013-09-24T11:40:47+0000 [-\x23-] XYZZY\n",
)
示例14: __init__
# 需要导入模块: import time [as 别名]
# 或者: from time import tzset [as 别名]
def __init__(self):
"""Set all attributes.
Order of methods called matters for dependency reasons.
The locale language is set at the offset and then checked again before
exiting. This is to make sure that the attributes were not set with a
mix of information from more than one locale. This would most likely
happen when using threads where one thread calls a locale-dependent
function while another thread changes the locale while the function in
the other thread is still running. Proper coding would call for
locks to prevent changing the locale while locale-dependent code is
running. The check here is done in case someone does not think about
doing this.
Only other possible issue is if someone changed the timezone and did
not call tz.tzset . That is an issue for the programmer, though,
since changing the timezone is worthless without that call.
"""
self.lang = _getlang()
self.__calc_weekday()
self.__calc_month()
self.__calc_am_pm()
self.__calc_timezone()
self.__calc_date_time()
if _getlang() != self.lang:
raise ValueError("locale changed during initialization")
示例15: __calc_timezone
# 需要导入模块: import time [as 别名]
# 或者: from time import tzset [as 别名]
def __calc_timezone(self):
# Set self.timezone by using time.tzname.
# Do not worry about possibility of time.tzname[0] == timetzname[1]
# and time.daylight; handle that in strptime .
#try:
#time.tzset()
#except AttributeError:
#pass
no_saving = frozenset(["utc", "gmt", time.tzname[0].lower()])
if time.daylight:
has_saving = frozenset([time.tzname[1].lower()])
else:
has_saving = frozenset()
self.timezone = (no_saving, has_saving)