Python time.tzset() Examples

The following are 30 code examples for showing how to use time.tzset(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module time , or try the search function .

Example 1
Project: glazier   Author: google   File: ntp_test.py    License: Apache License 2.0 6 votes vote down vote up
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
Project: browserscope   Author: elsigh   File: devappserver2.py    License: Apache License 2.0 6 votes vote down vote up
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 3
Project: ironpython2   Author: IronLanguages   File: _strptime.py    License: Apache License 2.0 6 votes vote down vote up
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 4
Project: ironpython2   Author: IronLanguages   File: test_strptime.py    License: Apache License 2.0 6 votes vote down vote up
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 5
Project: ironpython2   Author: IronLanguages   File: test_strptime.py    License: Apache License 2.0 6 votes vote down vote up
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 6
Project: aumfor   Author: virtualrealitysystems   File: timefmt.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 7
Project: aumfor   Author: virtualrealitysystems   File: timefmt.py    License: GNU General Public License v3.0 6 votes vote down vote up
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
Project: bioforum   Author: reBiocoder   File: signals.py    License: MIT License 6 votes vote down vote up
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 9
Project: Safejumper-for-Desktop   Author: proxysh   File: test_tzhelper.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 10
Project: Safejumper-for-Desktop   Author: proxysh   File: test_cftp.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 11
Project: Safejumper-for-Desktop   Author: proxysh   File: test_format.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 12
Project: Imogen   Author: CedricGuillemet   File: _strptime.py    License: MIT License 6 votes vote down vote up
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 13
Project: learn_python3_spider   Author: wistbean   File: test_tzhelper.py    License: MIT License 6 votes vote down vote up
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 14
Project: learn_python3_spider   Author: wistbean   File: test_cftp.py    License: MIT License 6 votes vote down vote up
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 15
Project: learn_python3_spider   Author: wistbean   File: test_format.py    License: MIT License 6 votes vote down vote up
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 16
Project: ironpython3   Author: IronLanguages   File: _strptime.py    License: Apache License 2.0 6 votes vote down vote up
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 17
Project: ironpython3   Author: IronLanguages   File: test_strptime.py    License: Apache License 2.0 6 votes vote down vote up
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 18
Project: ironpython3   Author: IronLanguages   File: test_strptime.py    License: Apache License 2.0 6 votes vote down vote up
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 19
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: signals.py    License: MIT License 6 votes vote down vote up
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 20
Project: python   Author: Yeah-Kun   File: signals.py    License: Apache License 2.0 6 votes vote down vote up
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 21
Project: volatility   Author: volatilityfoundation   File: timefmt.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 22
Project: volatility   Author: volatilityfoundation   File: timefmt.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 23
Project: vortessence   Author: vortessence   File: timefmt.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 24
Project: vortessence   Author: vortessence   File: timefmt.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 25
Project: DAMM   Author: 504ensicsLabs   File: timefmt.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 26
Project: jawfish   Author: war-and-code   File: _strptime.py    License: MIT License 5 votes vote down vote up
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 27
Project: jawfish   Author: war-and-code   File: _strptime.py    License: MIT License 5 votes vote down vote up
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 28
Project: jawfish   Author: war-and-code   File: support.py    License: MIT License 5 votes vote down vote up
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 29
Project: verge3d-blender-addon   Author: Soft8Soft   File: support.py    License: GNU General Public License v3.0 5 votes vote down vote up
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 30
Project: plugin.video.emby   Author: MediaBrowser   File: _common.py    License: GNU General Public License v3.0 5 votes vote down vote up
def set_current_tz(self, tzval):
        if tzval is UnsetTz and 'TZ' in os.environ:
            del os.environ['TZ']
        else:
            os.environ['TZ'] = tzval

        time.tzset()