Python time.tzset() Examples

The following are code examples for showing how to use time.tzset(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: glazier   Author: google   File: ntp_test.py    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: NiujiaoDebugger   Author: MrSrc   File: _strptime.py    GNU General Public License v3.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 3
Project: NiujiaoDebugger   Author: MrSrc   File: test_strptime.py    GNU General Public License v3.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 4
Project: NiujiaoDebugger   Author: MrSrc   File: test_strptime.py    GNU General Public License v3.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 5
Project: rig-remote   Author: Marzona   File: rig-remote.py    MIT License 6 votes vote down vote up
def log_configuration(verbose):
    """Logger configuration: time/date formatting.

    """

    os.environ["TZ"] = "UTC"

    # Windows doesn't support tzset. Ignore for now.
    try:
        time.tzset()
    except AttributeError:
        pass

    if verbose:
        logging.basicConfig(level=logging.INFO,
                            format="%(asctime)s %(message)s",
                            datefmt="%m/%d/%Y %I:%M:%S %p %Z")
    else:
        logging.basicConfig(level=logging.WARNING,
                            format="%(asctime)s %(message)s",
                            datefmt="%m/%d/%Y %I:%M:%S %p %Z")

    return logging.getLogger(__name__)

# entry point 
Example 6
Project: liberator   Author: libscie   File: signals.py    Creative Commons Zero v1.0 Universal 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 7
Project: ironpython2   Author: IronLanguages   File: _strptime.py    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 8
Project: ironpython2   Author: IronLanguages   File: test_strptime.py    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 9
Project: ironpython2   Author: IronLanguages   File: test_strptime.py    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 10
Project: banruo   Author: yingshang   File: signals.py    GNU Lesser General Public License v3.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 11
Project: open-recipe   Author: dspray95   File: test_tzhelper.py    The Unlicense 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 12
Project: open-recipe   Author: dspray95   File: test_cftp.py    The Unlicense 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 13
Project: open-recipe   Author: dspray95   File: test_format.py    The Unlicense 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 14
Project: Blockly-rduino-communication   Author: technologiescollege   File: _strptime.py    GNU General Public License v3.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 15
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_strptime.py    GNU General Public License v3.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 16
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_strptime.py    GNU General Public License v3.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 17
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: _strptime.py    GNU General Public License v2.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 18
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_strptime.py    GNU General Public License v2.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 19
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_strptime.py    GNU General Public License v2.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 20
Project: aws-lambda-runtime-pypy   Author: uscheller   File: _strptime.py    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 21
Project: news_proj   Author: TheoElia   File: signals.py    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 22
Project: Bookmark   Author: AnkurRyder   File: signals.py    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 23
Project: Safejumper-for-Desktop   Author: proxysh   File: test_tzhelper.py    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 24
Project: Safejumper-for-Desktop   Author: proxysh   File: test_cftp.py    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 25
Project: Safejumper-for-Desktop   Author: proxysh   File: test_format.py    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 26
Project: time2go   Author: twitchyliquid64   File: test_typeconversion.py    MIT License 6 votes vote down vote up
def testTimestampRoundtrip(self):
        v = datetime.datetime(2001, 2, 3, 4, 5, 6, 170000)
        self.cursor.execute("SELECT %s as f1", (v,))
        retval = self.cursor.fetchall()
        self.assertEqual(retval[0][0], v)

        # Test that time zone doesn't affect it
        # Jython 2.5.3 doesn't have a time.tzset() so skip
        if not IS_JYTHON:
            orig_tz = os.environ['TZ']
            os.environ['TZ'] = "America/Edmonton"
            time.tzset()

            self.cursor.execute("SELECT %s as f1", (v,))
            retval = self.cursor.fetchall()
            self.assertEqual(retval[0][0], v)

            os.environ['TZ'] = orig_tz
            time.tzset() 
Example 27
Project: pyblish-win   Author: pyblish   File: _strptime.py    GNU Lesser General Public License v3.0 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 28
Project: pyblish-win   Author: pyblish   File: _strptime.py    GNU Lesser General Public License v3.0 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 29
Project: jawfish   Author: war-and-code   File: _strptime.py    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 30
Project: jawfish   Author: war-and-code   File: _strptime.py    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 31
Project: jawfish   Author: war-and-code   File: support.py    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 32
Project: Repobot   Author: Desgard   File: support.py    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 33
Project: chattR   Author: patrickstocklin   File: signals.py    GNU General Public License v2.0 5 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'] == 'USE_TZ' and settings.TIME_ZONE != 'UTC':
        USE_TZ, TIME_ZONE = kwargs['value'], settings.TIME_ZONE
    elif kwargs['setting'] == 'TIME_ZONE' and not settings.USE_TZ:
        USE_TZ, TIME_ZONE = settings.USE_TZ, kwargs['value']
    else:
        # no need to change the database connnections' time zones
        return
    tz = 'UTC' if USE_TZ else TIME_ZONE
    for conn in connections.all():
        conn.settings_dict['TIME_ZONE'] = tz
        tz_sql = conn.ops.set_time_zone_sql()
        if tz_sql:
            conn.cursor().execute(tz_sql, [tz]) 
Example 34
Project: NiujiaoDebugger   Author: MrSrc   File: _strptime.py    GNU General Public License v3.0 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")
        if time.tzname != self.tzname or time.daylight != self.daylight:
            raise ValueError("timezone changed during initialization") 
Example 35
Project: NiujiaoDebugger   Author: MrSrc   File: __init__.py    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 36
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: testing.py    MIT License 5 votes vote down vote up
def set_timezone(tz):
    """Context manager for temporarily setting a timezone.

    Parameters
    ----------
    tz : str
        A string representing a valid timezone.

    Examples
    --------

    >>> from datetime import datetime
    >>> from dateutil.tz import tzlocal
    >>> tzlocal().tzname(datetime.now())
    'IST'

    >>> with set_timezone('US/Eastern'):
    ...     tzlocal().tzname(datetime.now())
    ...
    'EDT'
    """

    import os
    import time

    def setTZ(tz):
        if tz is None:
            try:
                del os.environ["TZ"]
            except KeyError:
                pass
        else:
            os.environ["TZ"] = tz
            time.tzset()

    orig_tz = os.environ.get("TZ")
    setTZ(tz)
    try:
        yield
    finally:
        setTZ(orig_tz) 
Example 37
Project: recruit   Author: Frank-qlu   File: testing.py    Apache License 2.0 5 votes vote down vote up
def set_timezone(tz):
    """Context manager for temporarily setting a timezone.

    Parameters
    ----------
    tz : str
        A string representing a valid timezone.

    Examples
    --------

    >>> from datetime import datetime
    >>> from dateutil.tz import tzlocal
    >>> tzlocal().tzname(datetime.now())
    'IST'

    >>> with set_timezone('US/Eastern'):
    ...     tzlocal().tzname(datetime.now())
    ...
    'EDT'
    """

    import os
    import time

    def setTZ(tz):
        if tz is None:
            try:
                del os.environ['TZ']
            except KeyError:
                pass
        else:
            os.environ['TZ'] = tz
            time.tzset()

    orig_tz = os.environ.get('TZ')
    setTZ(tz)
    try:
        yield
    finally:
        setTZ(orig_tz) 
Example 38
Project: peony-twitter   Author: odrling   File: birthday.py    MIT License 5 votes vote down vote up
def set_tz(self):
        """
            set the environment timezone to the timezone
            set in your twitter settings
        """
        settings = await self.api.account.settings.get()

        tz = settings.time_zone.tzinfo_name

        os.environ['TZ'] = tz
        time.tzset() 
Example 39
Project: TESTGIT   Author: B-ROY   File: signals.py    Apache License 2.0 5 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._localtime = None

    # Reset the database connections' time zone
    if kwargs['setting'] == 'USE_TZ' and settings.TIME_ZONE != 'UTC':
        USE_TZ, TIME_ZONE = kwargs['value'], settings.TIME_ZONE
    elif kwargs['setting'] == 'TIME_ZONE' and not settings.USE_TZ:
        USE_TZ, TIME_ZONE = settings.USE_TZ, kwargs['value']
    else:
        # no need to change the database connnections' time zones
        return
    tz = 'UTC' if USE_TZ else TIME_ZONE
    for conn in connections.all():
        conn.settings_dict['TIME_ZONE'] = tz
        tz_sql = conn.ops.set_time_zone_sql()
        if tz_sql:
            conn.cursor().execute(tz_sql, [tz]) 
Example 40
Project: AneMo   Author: jspargo   File: signals.py    GNU General Public License v2.0 5 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._localtime = None

    # Reset the database connections' time zone
    if kwargs['setting'] == 'USE_TZ' and settings.TIME_ZONE != 'UTC':
        USE_TZ, TIME_ZONE = kwargs['value'], settings.TIME_ZONE
    elif kwargs['setting'] == 'TIME_ZONE' and not settings.USE_TZ:
        USE_TZ, TIME_ZONE = settings.USE_TZ, kwargs['value']
    else:
        # no need to change the database connnections' time zones
        return
    tz = 'UTC' if USE_TZ else TIME_ZONE
    for conn in connections.all():
        conn.settings_dict['TIME_ZONE'] = tz
        tz_sql = conn.ops.set_time_zone_sql()
        if tz_sql:
            conn.cursor().execute(tz_sql, [tz]) 
Example 41
Project: GTDWeb   Author: lanbing510   File: signals.py    GNU General Public License v2.0 5 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'] == 'USE_TZ' and settings.TIME_ZONE != 'UTC':
        USE_TZ, TIME_ZONE = kwargs['value'], settings.TIME_ZONE
    elif kwargs['setting'] == 'TIME_ZONE' and not settings.USE_TZ:
        USE_TZ, TIME_ZONE = settings.USE_TZ, kwargs['value']
    else:
        # no need to change the database connnections' time zones
        return
    tz = 'UTC' if USE_TZ else TIME_ZONE
    for conn in connections.all():
        conn.settings_dict['TIME_ZONE'] = tz
        tz_sql = conn.ops.set_time_zone_sql()
        if tz_sql:
            conn.cursor().execute(tz_sql, [tz]) 
Example 42
Project: FUTU_Stop_Loss   Author: BigtoC   File: testing.py    MIT License 5 votes vote down vote up
def set_timezone(tz):
    """Context manager for temporarily setting a timezone.

    Parameters
    ----------
    tz : str
        A string representing a valid timezone.

    Examples
    --------

    >>> from datetime import datetime
    >>> from dateutil.tz import tzlocal
    >>> tzlocal().tzname(datetime.now())
    'IST'

    >>> with set_timezone('US/Eastern'):
    ...     tzlocal().tzname(datetime.now())
    ...
    'EDT'
    """

    import os
    import time

    def setTZ(tz):
        if tz is None:
            try:
                del os.environ['TZ']
            except KeyError:
                pass
        else:
            os.environ['TZ'] = tz
            time.tzset()

    orig_tz = os.environ.get('TZ')
    setTZ(tz)
    try:
        yield
    finally:
        setTZ(orig_tz) 
Example 43
Project: ironpython2   Author: IronLanguages   File: _strptime.py    Apache License 2.0 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")
        if time.tzname != self.tzname or time.daylight != self.daylight:
            raise ValueError("timezone changed during initialization") 
Example 44
Project: ironpython2   Author: IronLanguages   File: __init__.py    Apache License 2.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 45
Project: open-recipe   Author: dspray95   File: test_cftp.py    The Unlicense 5 votes vote down vote up
def _lsInTimezone(self, timezone, stat):
        """
        Call L{ls.lsLine} after setting the timezone to C{timezone} and return
        the result.
        """
        # Set the timezone to a well-known value so the timestamps are
        # predictable.
        os.environ['TZ'] = timezone
        time.tzset()
        return ls.lsLine('foo', stat) 
Example 46
Project: vnpy_crypto   Author: birforce   File: testing.py    MIT License 5 votes vote down vote up
def set_timezone(tz):
    """Context manager for temporarily setting a timezone.

    Parameters
    ----------
    tz : str
        A string representing a valid timezone.

    Examples
    --------

    >>> from datetime import datetime
    >>> from dateutil.tz import tzlocal
    >>> tzlocal().tzname(datetime.now())
    'IST'

    >>> with set_timezone('US/Eastern'):
    ...     tzlocal().tzname(datetime.now())
    ...
    'EDT'
    """

    import os
    import time

    def setTZ(tz):
        if tz is None:
            try:
                del os.environ['TZ']
            except KeyError:
                pass
        else:
            os.environ['TZ'] = tz
            time.tzset()

    orig_tz = os.environ.get('TZ')
    setTZ(tz)
    try:
        yield
    finally:
        setTZ(orig_tz) 
Example 47
Project: clusterfuzz   Author: google   File: dates.py    Apache License 2.0 5 votes vote down vote up
def initialize_timezone_from_environment():
  """Initializes timezone for date functions based on environment."""
  plt = environment.platform()
  if plt == 'WINDOWS':
    return

  # Only available on Unix platforms.
  time.tzset() 
Example 48
Project: indy-plenum   Author: hyperledger   File: test_util.py    Apache License 2.0 5 votes vote down vote up
def test_utc_epoch():
    t1 = get_utc_epoch()
    time.sleep(1)
    t2 = get_utc_epoch()
    assert 1 <= t2 - t1 <= 2

    old_tz = os.environ.get('TZ')

    t3 = get_utc_epoch()
    os.environ['TZ'] = 'Europe/London'
    time.tzset()
    time.sleep(1)
    t4 = get_utc_epoch()
    assert 1 <= t4 - t3 <= 2

    t5 = get_utc_epoch()
    os.environ['TZ'] = 'America/St_Johns'
    time.tzset()
    time.sleep(1)
    t6 = get_utc_epoch()
    assert 1 <= t6 - t5 <= 2

    if old_tz is None:
        del os.environ['TZ']
    else:
        os.environ['TZ'] = old_tz 
Example 49
Project: Blockly-rduino-communication   Author: technologiescollege   File: _strptime.py    GNU General Public License v3.0 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")
        if time.tzname != self.tzname or time.daylight != self.daylight:
            raise ValueError("timezone changed during initialization") 
Example 50
Project: Fun5G   Author: OpenWinCon   File: signals.py    Apache License 2.0 5 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'] == 'USE_TZ' and settings.TIME_ZONE != 'UTC':
        USE_TZ, TIME_ZONE = kwargs['value'], settings.TIME_ZONE
    elif kwargs['setting'] == 'TIME_ZONE' and not settings.USE_TZ:
        USE_TZ, TIME_ZONE = settings.USE_TZ, kwargs['value']
    else:
        # no need to change the database connnections' time zones
        return
    tz = 'UTC' if USE_TZ else TIME_ZONE
    for conn in connections.all():
        conn.settings_dict['TIME_ZONE'] = tz
        tz_sql = conn.ops.set_time_zone_sql()
        if tz_sql:
            conn.cursor().execute(tz_sql, [tz])