Python time.tzset() Examples
The following are 30
code examples of time.tzset().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
time
, or try the search function
.
Example #1
Source File: ntp_test.py From glazier with Apache License 2.0 | 6 votes |
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)
Example #2
Source File: signals.py From python with Apache License 2.0 | 6 votes |
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()
Example #3
Source File: test_strptime.py From ironpython2 with Apache License 2.0 | 6 votes |
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))
Example #4
Source File: devappserver2.py From browserscope with Apache License 2.0 | 6 votes |
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()
Example #5
Source File: timefmt.py From volatility with GNU General Public License v2.0 | 6 votes |
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)
Example #6
Source File: timefmt.py From vortessence with GNU General Public License v2.0 | 6 votes |
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
Example #7
Source File: timefmt.py From volatility with GNU General Public License v2.0 | 6 votes |
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
Example #8
Source File: timefmt.py From vortessence with GNU General Public License v2.0 | 6 votes |
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)
Example #9
Source File: _strptime.py From ironpython2 with Apache License 2.0 | 6 votes |
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)
Example #10
Source File: test_strptime.py From ironpython2 with Apache License 2.0 | 6 votes |
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')
Example #11
Source File: timefmt.py From aumfor with GNU General Public License v3.0 | 6 votes |
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)
Example #12
Source File: timefmt.py From aumfor with GNU General Public License v3.0 | 6 votes |
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
Example #13
Source File: signals.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
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()
Example #14
Source File: signals.py From bioforum with MIT License | 6 votes |
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()
Example #15
Source File: timefmt.py From DAMM with GNU General Public License v2.0 | 6 votes |
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)
Example #16
Source File: test_format.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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", )
Example #17
Source File: _strptime.py From Imogen with MIT License | 6 votes |
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)
Example #18
Source File: test_cftp.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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)
Example #19
Source File: test_tzhelper.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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()
Example #20
Source File: test_tzhelper.py From learn_python3_spider with MIT License | 6 votes |
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()
Example #21
Source File: test_cftp.py From learn_python3_spider with MIT License | 6 votes |
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)
Example #22
Source File: test_format.py From learn_python3_spider with MIT License | 6 votes |
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", )
Example #23
Source File: _strptime.py From ironpython3 with Apache License 2.0 | 6 votes |
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)
Example #24
Source File: test_strptime.py From ironpython3 with Apache License 2.0 | 6 votes |
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))
Example #25
Source File: test_strptime.py From ironpython3 with Apache License 2.0 | 6 votes |
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')
Example #26
Source File: support.py From telegram-robot-rss with Mozilla Public License 2.0 | 5 votes |
def run_with_tz(tz): def decorator(func): def inner(*args, **kwds): try: tzset = time.tzset except AttributeError: raise unittest.SkipTest("tzset required") if 'TZ' in os.environ: orig_tz = os.environ['TZ'] else: orig_tz = None os.environ['TZ'] = tz tzset() # now run the function, resetting the tz on exceptions try: return func(*args, **kwds) finally: if orig_tz is None: del os.environ['TZ'] else: os.environ['TZ'] = orig_tz time.tzset() inner.__name__ = func.__name__ inner.__doc__ = func.__doc__ return inner return decorator #======================================================================= # Big-memory-test support. Separate from 'resources' because memory use # should be configurable. # Some handy shorthands. Note that these are used for byte-limits as well # as size-limits, in the various bigmem tests
Example #27
Source File: _strptime.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
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")
Example #28
Source File: _strptime.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
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)
Example #29
Source File: _strptime.py From pmatic with GNU General Public License v2.0 | 5 votes |
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)
Example #30
Source File: time_utils.py From python-smime with Apache License 2.0 | 5 votes |
def timezone(temp_tz): """Sets the timezone, yields, then resets the timezone. Args: temp_tz: See https://docs.python.org/2/library/time.html#time.tzset """ original_tz = get_timezone_environ() set_timezone_environ(temp_tz) try: yield finally: set_timezone_environ(original_tz)