Python time.tzname() Examples

The following are code examples for showing how to use time.tzname(). 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: pyblish-win   Author: pyblish   File: test_strftime.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _update_variables(self, now):
        # we must update the local variables on every cycle
        self.gmt = time.gmtime(now)
        now = time.localtime(now)

        if now[3] < 12: self.ampm='(AM|am)'
        else: self.ampm='(PM|pm)'

        self.jan1 = time.localtime(time.mktime((now[0], 1, 1, 0, 0, 0, 0, 1, 0)))

        try:
            if now[8]: self.tz = time.tzname[1]
            else: self.tz = time.tzname[0]
        except AttributeError:
            self.tz = ''

        if now[3] > 12: self.clock12 = now[3] - 12
        elif now[3] > 0: self.clock12 = now[3]
        else: self.clock12 = 12

        self.now = now 
Example 2
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_timezone(self):
        # Test timezone directives.
        # When gmtime() is used with %Z, entire result of strftime() is empty.
        # Check for equal timezone names deals with bad locale info when this
        # occurs; first found in FreeBSD 4.4.
        strp_output = _strptime._strptime_time("UTC", "%Z")
        self.assertEqual(strp_output.tm_isdst, 0)
        strp_output = _strptime._strptime_time("GMT", "%Z")
        self.assertEqual(strp_output.tm_isdst, 0)
        time_tuple = time.localtime()
        strf_output = time.strftime("%Z")  #UTC does not have a timezone
        strp_output = _strptime._strptime_time(strf_output, "%Z")
        locale_time = _strptime.LocaleTime()
        if time.tzname[0] != time.tzname[1] or not time.daylight:
            self.assertTrue(strp_output[8] == time_tuple[8],
                            "timezone check failed; '%s' -> %s != %s" %
                             (strf_output, strp_output[8], time_tuple[8]))
        else:
            self.assertTrue(strp_output[8] == -1,
                            "LocaleTime().timezone has duplicate values and "
                             "time.daylight but timezone value not set to -1") 
Example 3
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser 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')
        try:
            original_tzname = time.tzname
            original_daylight = time.daylight
            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))
        finally:
            time.tzname = original_tzname
            time.daylight = original_daylight 
Example 4
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 5
Project: NiujiaoDebugger   Author: MrSrc   File: test_strftime.py    GNU General Public License v3.0 6 votes vote down vote up
def _update_variables(self, now):
        # we must update the local variables on every cycle
        self.gmt = time.gmtime(now)
        now = time.localtime(now)

        if now[3] < 12: self.ampm='(AM|am)'
        else: self.ampm='(PM|pm)'

        self.jan1 = time.localtime(time.mktime((now[0], 1, 1, 0, 0, 0, 0, 1, 0)))

        try:
            if now[8]: self.tz = time.tzname[1]
            else: self.tz = time.tzname[0]
        except AttributeError:
            self.tz = ''

        if now[3] > 12: self.clock12 = now[3] - 12
        elif now[3] > 0: self.clock12 = now[3]
        else: self.clock12 = 12

        self.now = now 
Example 6
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 7
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 8
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 6 votes vote down vote up
def test_pickling_subclass(self):
        # Make sure we can pickle/unpickle an instance of a subclass.
        offset = timedelta(minutes=-300)
        for otype, args in [
            (PicklableFixedOffset, (offset, 'cookie')),
            (timezone, (offset,)),
            (timezone, (offset, "EST"))]:
            orig = otype(*args)
            oname = orig.tzname(None)
            self.assertIsInstance(orig, tzinfo)
            self.assertIs(type(orig), otype)
            self.assertEqual(orig.utcoffset(None), offset)
            self.assertEqual(orig.tzname(None), oname)
            for pickler, unpickler, proto in pickle_choices:
                green = pickler.dumps(orig, proto)
                derived = unpickler.loads(green)
                self.assertIsInstance(derived, tzinfo)
                self.assertIs(type(derived), otype)
                self.assertEqual(derived.utcoffset(None), offset)
                self.assertEqual(derived.tzname(None), oname) 
Example 9
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 6 votes vote down vote up
def test_issue23600(self):
        DSTDIFF = DSTOFFSET = timedelta(hours=1)

        class UKSummerTime(tzinfo):
            """Simple time zone which pretends to always be in summer time, since
                that's what shows the failure.
            """

            def utcoffset(self, dt):
                return DSTOFFSET

            def dst(self, dt):
                return DSTDIFF

            def tzname(self, dt):
                return 'UKSummerTime'

        tz = UKSummerTime()
        u = datetime(2014, 4, 26, 12, 1, tzinfo=tz)
        t = tz.fromutc(u)
        self.assertEqual(t - t.utcoffset(), u) 
Example 10
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 6 votes vote down vote up
def test_argument_passing(self):
        cls = self.theclass
        # A datetime passes itself on, a time passes None.
        class introspective(tzinfo):
            def tzname(self, dt):    return dt and "real" or "none"
            def utcoffset(self, dt):
                return timedelta(minutes = dt and 42 or -42)
            dst = utcoffset

        obj = cls(1, 2, 3, tzinfo=introspective())

        expected = cls is time and "none" or "real"
        self.assertEqual(obj.tzname(), expected)

        expected = timedelta(minutes=(cls is time and -42 or 42))
        self.assertEqual(obj.utcoffset(), expected)
        self.assertEqual(obj.dst(), expected) 
Example 11
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 6 votes vote down vote up
def test_pickling(self):
        # Try one without a tzinfo.
        args = 6, 7, 23, 20, 59, 1, 64**2
        orig = self.theclass(*args)
        for pickler, unpickler, proto in pickle_choices:
            green = pickler.dumps(orig, proto)
            derived = unpickler.loads(green)
            self.assertEqual(orig, derived)
        self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2))

        # Try one with a tzinfo.
        tinfo = PicklableFixedOffset(-300, 'cookie')
        orig = self.theclass(*args, **{'tzinfo': tinfo})
        derived = self.theclass(1, 1, 1, tzinfo=FixedOffset(0, "", 0))
        for pickler, unpickler, proto in pickle_choices:
            green = pickler.dumps(orig, proto)
            derived = unpickler.loads(green)
            self.assertEqual(orig, derived)
            self.assertIsInstance(derived.tzinfo, PicklableFixedOffset)
            self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
            self.assertEqual(derived.tzname(), 'cookie')
        self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2)) 
Example 12
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 13
Project: Splunk_CBER_App   Author: MHaggis   File: tz.py    MIT License 5 votes vote down vote up
def tzname_in_python2(myfunc):
    """Change unicode output into bytestrings in Python 2

    tzname() API changed in Python 3. It used to return bytes, but was changed
    to unicode strings
    """
    def inner_func(*args, **kwargs):
        if PY3:
            return myfunc(*args, **kwargs)
        else:
            return myfunc(*args, **kwargs).encode()
    return inner_func 
Example 14
Project: Splunk_CBER_App   Author: MHaggis   File: tz.py    MIT License 5 votes vote down vote up
def tzname(self, dt):
        return "UTC" 
Example 15
Project: Splunk_CBER_App   Author: MHaggis   File: tz.py    MIT License 5 votes vote down vote up
def tzname(self, dt):
        return self._name 
Example 16
Project: Splunk_CBER_App   Author: MHaggis   File: tz.py    MIT License 5 votes vote down vote up
def tzname(self, dt):
        return time.tzname[self._isdst(dt)] 
Example 17
Project: Splunk_CBER_App   Author: MHaggis   File: tz.py    MIT License 5 votes vote down vote up
def _isdst(self, dt):
        # We can't use mktime here. It is unstable when deciding if
        # the hour near to a change is DST or not.
        #
        # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour,
        #                         dt.minute, dt.second, dt.weekday(), 0, -1))
        # return time.localtime(timestamp).tm_isdst
        #
        # The code above yields the following result:
        #
        # >>> import tz, datetime
        # >>> t = tz.tzlocal()
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRDT'
        # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname()
        # 'BRST'
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRST'
        # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname()
        # 'BRDT'
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRDT'
        #
        # Here is a more stable implementation:
        #
        timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400
                     + dt.hour * 3600
                     + dt.minute * 60
                     + dt.second)
        return time.localtime(timestamp+time.timezone).tm_isdst 
Example 18
Project: Splunk_CBER_App   Author: MHaggis   File: tz.py    MIT License 5 votes vote down vote up
def tzname(self, dt):
        if self._isdst(dt):
            return self._dst_abbr
        else:
            return self._std_abbr 
Example 19
Project: Splunk_CBER_App   Author: MHaggis   File: tz.py    MIT License 5 votes vote down vote up
def __init__(self, tzoffsetfrom, tzoffsetto, isdst,
                 tzname=None, rrule=None):
        self.tzoffsetfrom = datetime.timedelta(seconds=tzoffsetfrom)
        self.tzoffsetto = datetime.timedelta(seconds=tzoffsetto)
        self.tzoffsetdiff = self.tzoffsetto-self.tzoffsetfrom
        self.isdst = isdst
        self.tzname = tzname
        self.rrule = rrule 
Example 20
Project: Splunk_CBER_App   Author: MHaggis   File: tz.py    MIT License 5 votes vote down vote up
def tzname(self, dt):
        return self._find_comp(dt).tzname 
Example 21
Project: Splunk_CBER_App   Author: MHaggis   File: parser.py    MIT License 5 votes vote down vote up
def validate(self, res):
        # move to info
        if res.year is not None:
            res.year = self.convertyear(res.year)

        if res.tzoffset == 0 and not res.tzname or res.tzname == 'Z':
            res.tzname = "UTC"
            res.tzoffset = 0
        elif res.tzoffset != 0 and res.tzname and self.utczone(res.tzname):
            res.tzoffset = 0
        return True 
Example 22
Project: bigquerylayers   Author: smandaric   File: reference.py    GNU General Public License v3.0 5 votes vote down vote up
def tzname(self, dt):
        return self.__name 
Example 23
Project: bigquerylayers   Author: smandaric   File: reference.py    GNU General Public License v3.0 5 votes vote down vote up
def tzname(self, dt):
        return _time.tzname[self._isdst(dt)] 
Example 24
Project: bigquerylayers   Author: smandaric   File: reference.py    GNU General Public License v3.0 5 votes vote down vote up
def tzname(self, dt):
        if self.dst(dt):
            return self.dstname
        else:
            return self.stdname 
Example 25
Project: AshsSDK   Author: thehappydinoa   File: tz.py    MIT License 5 votes vote down vote up
def tzname(self, dt):
        return "UTC" 
Example 26
Project: AshsSDK   Author: thehappydinoa   File: tz.py    MIT License 5 votes vote down vote up
def tzname(self, dt):
        return self._name 
Example 27
Project: AshsSDK   Author: thehappydinoa   File: tz.py    MIT License 5 votes vote down vote up
def tzname(self, dt):
        return time.tzname[self._isdst(dt)] 
Example 28
Project: AshsSDK   Author: thehappydinoa   File: tz.py    MIT License 5 votes vote down vote up
def _isdst(self, dt, fold_naive=True):
        # We can't use mktime here. It is unstable when deciding if
        # the hour near to a change is DST or not.
        #
        # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour,
        #                         dt.minute, dt.second, dt.weekday(), 0, -1))
        # return time.localtime(timestamp).tm_isdst
        #
        # The code above yields the following result:
        #
        # >>> import tz, datetime
        # >>> t = tz.tzlocal()
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRDT'
        # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname()
        # 'BRST'
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRST'
        # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname()
        # 'BRDT'
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRDT'
        #
        # Here is a more stable implementation:
        #
        if not self._hasdst:
            return False

        # Check for ambiguous times:
        dstval = self._naive_is_dst(dt)
        fold = getattr(dt, 'fold', None)

        if self.is_ambiguous(dt):
            if fold is not None:
                return not self._fold(dt)
            else:
                return True

        return dstval 
Example 29
Project: AshsSDK   Author: thehappydinoa   File: tz.py    MIT License 5 votes vote down vote up
def tzname(self, dt):
        if not self._ttinfo_std or dt is None:
            return None
        return self._find_ttinfo(dt).abbr 
Example 30
Project: AshsSDK   Author: thehappydinoa   File: tz.py    MIT License 5 votes vote down vote up
def tzname(self, dt):
        return self._find_comp(dt).tzname 
Example 31
Project: AshsSDK   Author: thehappydinoa   File: parser.py    MIT License 5 votes vote down vote up
def validate(self, res):
        # move to info
        if res.year is not None:
            res.year = self.convertyear(res.year, res.century_specified)

        if res.tzoffset == 0 and not res.tzname or res.tzname == 'Z':
            res.tzname = "UTC"
            res.tzoffset = 0
        elif res.tzoffset != 0 and res.tzname and self.utczone(res.tzname):
            res.tzoffset = 0
        return True 
Example 32
Project: Old-school-processing   Author: cianfrocco-lab   File: tiltfile.py    MIT License 5 votes vote down vote up
def saveData(savedata, filename, filetype=None):
	"""
	savedata = {}
	savedata['theta'] = self.data['theta']
	savedata['gamma'] = self.data['gamma']
	savedata['phi'] = self.data['phi']
	savedata['savetime'] = time.asctime()+" "+time.tzname[time.daylight]
	savedata['filetype'] = tiltfile.filetypes[self.data['filetypeindex']]
	savedata['picks1'] = self.getArray1()
	savedata['picks2'] = self.getArray2()
	savedata['align1'] = self.getAlignedArray1()
	savedata['align2'] = self.getAlignedArray2()
	savedata['rmsd'] = self.getRmsdArray()
	savedata['image1name'] = self.panel1.filename
	savedata['image2name'] = self.panel2.filename
	"""

	if filetype is None:
		filetype = guessFileType(filename)

	savedata['savetime'] = time.asctime()+" "+time.tzname[time.daylight]
	savedata['filetype'] = filetype
	savedata['filename'] = os.path.basename(filename)

	if filetype == 'text':
		saveToTextFile(savedata, filename)
	elif filetype == 'xml':
		saveToXMLFile(savedata, filename)
	elif filetype == 'spider':
		saveToSpiderFile(savedata, filename)
	elif filetype == 'pickle':
		saveToPickleFile(savedata, filename)
	elif filetype == 'box':
		saveToBoxFile(savedata, filename)
	else:
		return False
		apDisplay.printWarning("unknown file type")

#--------------------------------------- 
Example 33
Project: openhatch   Author: campbe13   File: reference.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def tzname(self, dt):
        return self.__name 
Example 34
Project: openhatch   Author: campbe13   File: reference.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def tzname(self, dt):
        return _time.tzname[self._isdst(dt)] 
Example 35
Project: openhatch   Author: campbe13   File: reference.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def tzname(self, dt):
        if self.dst(dt):
            return self.dstname
        else:
            return self.stdname 
Example 36
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 37
Project: jawfish   Author: war-and-code   File: _strptime.py    MIT License 5 votes vote down vote up
def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):
    """Return a class cls instance based on the input string and the
    format string."""
    tt, fraction = _strptime(data_string, format)
    tzname, gmtoff = tt[-2:]
    args = tt[:6] + (fraction,)
    if gmtoff is not None:
        tzdelta = datetime_timedelta(seconds=gmtoff)
        if tzname:
            tz = datetime_timezone(tzdelta, tzname)
        else:
            tz = datetime_timezone(tzdelta)
        args += (tz,)
    return cls(*args) 
Example 38
Project: jawfish   Author: war-and-code   File: datetime.py    MIT License 5 votes vote down vote up
def _check_tzname(name):
    if name is not None and not isinstance(name, str):
        raise TypeError("tzinfo.tzname() must return None or string, "
                        "not '%s'" % type(name))

# name is the offset-producing method, "utcoffset" or "dst".
# offset is what it returned.
# If offset isn't None or timedelta, raises TypeError.
# If offset is None, returns None.
# Else offset is checked for being in range, and a whole # of minutes.
# If it is, its integer value is returned.  Else ValueError is raised. 
Example 39
Project: jawfish   Author: war-and-code   File: datetime.py    MIT License 5 votes vote down vote up
def tzname(self, dt):
        "datetime -> string name of time zone."
        raise NotImplementedError("tzinfo subclass must override tzname()") 
Example 40
Project: jawfish   Author: war-and-code   File: datetime.py    MIT License 5 votes vote down vote up
def tzname(self):
        """Return the timezone name.

        Note that the name is 100% informational -- there's no requirement that
        it mean anything in particular. For example, "GMT", "UTC", "-500",
        "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
        """
        name = _call_tzinfo_method(self._tzinfo, "tzname", self)
        _check_tzname(name)
        return name 
Example 41
Project: jawfish   Author: war-and-code   File: datetime.py    MIT License 5 votes vote down vote up
def __str__(self):
        return self.tzname(None) 
Example 42
Project: jawfish   Author: war-and-code   File: datetime.py    MIT License 5 votes vote down vote up
def tzname(self, dt):
        if isinstance(dt, datetime) or dt is None:
            if self._name is None:
                return self._name_from_offset(self._offset)
            return self._name
        raise TypeError("tzname() argument must be a datetime instance"
                        " or None") 
Example 43
Project: Repobot   Author: Desgard   File: utils.py    MIT License 5 votes vote down vote up
def localtime(dt=None, isdst=-1):
    """Return local time as an aware datetime object.

    If called without arguments, return current time.  Otherwise *dt*
    argument should be a datetime instance, and it is converted to the
    local time zone according to the system time zone database.  If *dt* is
    naive (that is, dt.tzinfo is None), it is assumed to be in local time.
    In this case, a positive or zero value for *isdst* causes localtime to
    presume initially that summer time (for example, Daylight Saving Time)
    is or is not (respectively) in effect for the specified time.  A
    negative value for *isdst* causes the localtime() function to attempt
    to divine whether summer time is in effect for the specified time.

    """
    if dt is None:
        return datetime.datetime.now(datetime.timezone.utc).astimezone()
    if dt.tzinfo is not None:
        return dt.astimezone()
    # We have a naive datetime.  Convert to a (localtime) timetuple and pass to
    # system mktime together with the isdst hint.  System mktime will return
    # seconds since epoch.
    tm = dt.timetuple()[:-1] + (isdst,)
    seconds = time.mktime(tm)
    localtm = time.localtime(seconds)
    try:
        delta = datetime.timedelta(seconds=localtm.tm_gmtoff)
        tz = datetime.timezone(delta, localtm.tm_zone)
    except AttributeError:
        # Compute UTC offset and compare with the value implied by tm_isdst.
        # If the values match, use the zone name implied by tm_isdst.
        delta = dt - datetime.datetime(*time.gmtime(seconds)[:6])
        dst = time.daylight and localtm.tm_isdst > 0
        gmtoff = -(time.altzone if dst else time.timezone)
        if delta == datetime.timedelta(seconds=gmtoff):
            tz = datetime.timezone(delta, time.tzname[dst])
        else:
            tz = datetime.timezone(delta)
    return dt.replace(tzinfo=tz) 
Example 44
Project: Repobot   Author: Desgard   File: datetime.py    MIT License 5 votes vote down vote up
def _check_tzname(name):
    if name is not None and not isinstance(name, str):
        raise TypeError("tzinfo.tzname() must return None or string, "
                        "not '%s'" % type(name))

# name is the offset-producing method, "utcoffset" or "dst".
# offset is what it returned.
# If offset isn't None or timedelta, raises TypeError.
# If offset is None, returns None.
# Else offset is checked for being in range, and a whole # of minutes.
# If it is, its integer value is returned.  Else ValueError is raised. 
Example 45
Project: Repobot   Author: Desgard   File: datetime.py    MIT License 5 votes vote down vote up
def tzname(self, dt):
        "datetime -> string name of time zone."
        raise NotImplementedError("tzinfo subclass must override tzname()") 
Example 46
Project: Repobot   Author: Desgard   File: datetime.py    MIT License 5 votes vote down vote up
def tzname(self):
        """Return the timezone name.

        Note that the name is 100% informational -- there's no requirement that
        it mean anything in particular. For example, "GMT", "UTC", "-500",
        "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
        """
        if self._tzinfo is None:
            return None
        name = self._tzinfo.tzname(None)
        _check_tzname(name)
        return name 
Example 47
Project: Repobot   Author: Desgard   File: datetime.py    MIT License 5 votes vote down vote up
def tzname(self):
        """Return the timezone name.

        Note that the name is 100% informational -- there's no requirement that
        it mean anything in particular. For example, "GMT", "UTC", "-500",
        "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies.
        """
        name = _call_tzinfo_method(self._tzinfo, "tzname", self)
        _check_tzname(name)
        return name 
Example 48
Project: Repobot   Author: Desgard   File: datetime.py    MIT License 5 votes vote down vote up
def __str__(self):
        return self.tzname(None) 
Example 49
Project: Repobot   Author: Desgard   File: datetime.py    MIT License 5 votes vote down vote up
def tzname(self, dt):
        if isinstance(dt, datetime) or dt is None:
            if self._name is None:
                return self._name_from_offset(self._offset)
            return self._name
        raise TypeError("tzname() argument must be a datetime instance"
                        " or None") 
Example 50
Project: chattR   Author: patrickstocklin   File: tzinfo.py    GNU General Public License v2.0 5 votes vote down vote up
def tzname(self, dt):
        return self.__name 
Example 51
Project: chattR   Author: patrickstocklin   File: tzinfo.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, dt):
        warnings.warn(
            "django.utils.tzinfo.LocalTimezone will be removed in Django 1.9. "
            "Use django.utils.timezone.get_default_timezone instead.",
            RemovedInDjango19Warning)
        tzinfo.__init__(self)
        self.__dt = dt
        self._tzname = self.tzname(dt) 
Example 52
Project: chattR   Author: patrickstocklin   File: tzinfo.py    GNU General Public License v2.0 5 votes vote down vote up
def tzname(self, dt):
        is_dst = False if dt is None else self._isdst(dt)
        try:
            return force_text(time.tzname[is_dst], DEFAULT_LOCALE_ENCODING)
        except UnicodeDecodeError:
            return None 
Example 53
Project: chattR   Author: patrickstocklin   File: timezone.py    GNU General Public License v2.0 5 votes vote down vote up
def tzname(self, dt):
        return "UTC" 
Example 54
Project: chattR   Author: patrickstocklin   File: timezone.py    GNU General Public License v2.0 5 votes vote down vote up
def tzname(self, dt):
        return self.__name 
Example 55
Project: chattR   Author: patrickstocklin   File: timezone.py    GNU General Public License v2.0 5 votes vote down vote up
def tzname(self, dt):
        is_dst = False if dt is None else self._isdst(dt)
        return _time.tzname[is_dst] 
Example 56
Project: chattR   Author: patrickstocklin   File: timezone.py    GNU General Public License v2.0 5 votes vote down vote up
def _get_timezone_name(timezone):
    """
    Returns the name of ``timezone``.
    """
    try:
        # for pytz timezones
        return timezone.zone
    except AttributeError:
        # for regular tzinfo objects
        return timezone.tzname(None)

# Timezone selection functions.

# These functions don't change os.environ['TZ'] and call time.tzset()
# because it isn't thread safe. 
Example 57
Project: epg-dk.bundle   Author: ukdtom   File: reference.py    The Unlicense 5 votes vote down vote up
def tzname(self, dt):
        return self.__name 
Example 58
Project: epg-dk.bundle   Author: ukdtom   File: reference.py    The Unlicense 5 votes vote down vote up
def tzname(self, dt):
        return _time.tzname[self._isdst(dt)] 
Example 59
Project: epg-dk.bundle   Author: ukdtom   File: reference.py    The Unlicense 5 votes vote down vote up
def tzname(self, dt):
        if self.dst(dt):
            return self.dstname
        else:
            return self.stdname 
Example 60
Project: NiujiaoDebugger   Author: MrSrc   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def localtime(dt=None, isdst=-1):
    """Return local time as an aware datetime object.

    If called without arguments, return current time.  Otherwise *dt*
    argument should be a datetime instance, and it is converted to the
    local time zone according to the system time zone database.  If *dt* is
    naive (that is, dt.tzinfo is None), it is assumed to be in local time.
    In this case, a positive or zero value for *isdst* causes localtime to
    presume initially that summer time (for example, Daylight Saving Time)
    is or is not (respectively) in effect for the specified time.  A
    negative value for *isdst* causes the localtime() function to attempt
    to divine whether summer time is in effect for the specified time.

    """
    if dt is None:
        return datetime.datetime.now(datetime.timezone.utc).astimezone()
    if dt.tzinfo is not None:
        return dt.astimezone()
    # We have a naive datetime.  Convert to a (localtime) timetuple and pass to
    # system mktime together with the isdst hint.  System mktime will return
    # seconds since epoch.
    tm = dt.timetuple()[:-1] + (isdst,)
    seconds = time.mktime(tm)
    localtm = time.localtime(seconds)
    try:
        delta = datetime.timedelta(seconds=localtm.tm_gmtoff)
        tz = datetime.timezone(delta, localtm.tm_zone)
    except AttributeError:
        # Compute UTC offset and compare with the value implied by tm_isdst.
        # If the values match, use the zone name implied by tm_isdst.
        delta = dt - datetime.datetime(*time.gmtime(seconds)[:6])
        dst = time.daylight and localtm.tm_isdst > 0
        gmtoff = -(time.altzone if dst else time.timezone)
        if delta == datetime.timedelta(seconds=gmtoff):
            tz = datetime.timezone(delta, time.tzname[dst])
        else:
            tz = datetime.timezone(delta)
    return dt.replace(tzinfo=tz) 
Example 61
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 62
Project: NiujiaoDebugger   Author: MrSrc   File: _strptime.py    GNU General Public License v3.0 5 votes vote down vote up
def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):
    """Return a class cls instance based on the input string and the
    format string."""
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
    tzname, gmtoff = tt[-2:]
    args = tt[:6] + (fraction,)
    if gmtoff is not None:
        tzdelta = datetime_timedelta(seconds=gmtoff, microseconds=gmtoff_fraction)
        if tzname:
            tz = datetime_timezone(tzdelta, tzname)
        else:
            tz = datetime_timezone(tzdelta)
        args += (tz,)

    return cls(*args) 
Example 63
Project: NiujiaoDebugger   Author: MrSrc   File: test_time.py    GNU General Public License v3.0 5 votes vote down vote up
def test_mktime_error(self):
        # It may not be possible to reliably make mktime return error
        # on all platfom.  This will make sure that no other exception
        # than OverflowError is raised for an extreme value.
        tt = time.gmtime(self.t)
        tzname = time.strftime('%Z', tt)
        self.assertNotEqual(tzname, 'LMT')
        try:
            time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
        except OverflowError:
            pass
        self.assertEqual(time.strftime('%Z', tt), tzname) 
Example 64
Project: NiujiaoDebugger   Author: MrSrc   File: test_time.py    GNU General Public License v3.0 5 votes vote down vote up
def test_localtime_timezone(self):

        # Get the localtime and examine it for the offset and zone.
        lt = time.localtime()
        self.assertTrue(hasattr(lt, "tm_gmtoff"))
        self.assertTrue(hasattr(lt, "tm_zone"))

        # See if the offset and zone are similar to the module
        # attributes.
        if lt.tm_gmtoff is None:
            self.assertTrue(not hasattr(time, "timezone"))
        else:
            self.assertEqual(lt.tm_gmtoff, -[time.timezone, time.altzone][lt.tm_isdst])
        if lt.tm_zone is None:
            self.assertTrue(not hasattr(time, "tzname"))
        else:
            self.assertEqual(lt.tm_zone, time.tzname[lt.tm_isdst])

        # Try and make UNIX times from the localtime and a 9-tuple
        # created from the localtime. Test to see that the times are
        # the same.
        t = time.mktime(lt); t9 = time.mktime(lt[:9])
        self.assertEqual(t, t9)

        # Make localtimes from the UNIX times and compare them to
        # the original localtime, thus making a round trip.
        new_lt = time.localtime(t); new_lt9 = time.localtime(t9)
        self.assertEqual(new_lt, lt)
        self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
        self.assertEqual(new_lt.tm_zone, lt.tm_zone)
        self.assertEqual(new_lt9, lt)
        self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff)
        self.assertEqual(new_lt9.tm_zone, lt.tm_zone) 
Example 65
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def tzname(self, dt):
        return self.__name 
Example 66
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_subclass_must_override(self):
        class NotEnough(tzinfo):
            def __init__(self, offset, name):
                self.__offset = offset
                self.__name = name
        self.assertTrue(issubclass(NotEnough, tzinfo))
        ne = NotEnough(3, "NotByALongShot")
        self.assertIsInstance(ne, tzinfo)

        dt = datetime.now()
        self.assertRaises(NotImplementedError, ne.tzname, dt)
        self.assertRaises(NotImplementedError, ne.utcoffset, dt)
        self.assertRaises(NotImplementedError, ne.dst, dt) 
Example 67
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_normal(self):
        fo = FixedOffset(3, "Three")
        self.assertIsInstance(fo, tzinfo)
        for dt in datetime.now(), None:
            self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3))
            self.assertEqual(fo.tzname(dt), "Three")
            self.assertEqual(fo.dst(dt), timedelta(minutes=42)) 
Example 68
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_str(self):
        for tz in [self.ACDT, self.EST, timezone.utc,
                   timezone.min, timezone.max]:
            self.assertEqual(str(tz), tz.tzname(None)) 
Example 69
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_aware_datetime(self):
        # test that timezone instances can be used by datetime
        t = datetime(1, 1, 1)
        for tz in [timezone.min, timezone.max, timezone.utc]:
            self.assertEqual(tz.tzname(t),
                             t.replace(tzinfo=tz).tzname())
            self.assertEqual(tz.utcoffset(t),
                             t.replace(tzinfo=tz).utcoffset())
            self.assertEqual(tz.dst(t),
                             t.replace(tzinfo=tz).dst()) 
Example 70
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_strftime_with_bad_tzname_replace(self):
        # verify ok if tzinfo.tzname().replace() returns a non-string
        class MyTzInfo(FixedOffset):
            def tzname(self, dt):
                class MyStr(str):
                    def replace(self, *args):
                        return None
                return MyStr('name')
        t = self.theclass(2005, 3, 2, 0, 0, 0, 0, MyTzInfo(3, 'name'))
        self.assertRaises(TypeError, t.strftime, '%Z') 
Example 71
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_compat_unpickle(self):
        tests = [
            b"cdatetime\ntime\n(S'\\x05\\x06\\x07\\x01\\xe2@'\n"
            b"ctest.datetimetester\nPicklableFixedOffset\n(tR"
            b"(dS'_FixedOffset__offset'\ncdatetime\ntimedelta\n"
            b"(I-1\nI68400\nI0\ntRs"
            b"S'_FixedOffset__dstoffset'\nNs"
            b"S'_FixedOffset__name'\nS'cookie'\nsbtR.",

            b'cdatetime\ntime\n(U\x06\x05\x06\x07\x01\xe2@'
            b'ctest.datetimetester\nPicklableFixedOffset\n)R'
            b'}(U\x14_FixedOffset__offsetcdatetime\ntimedelta\n'
            b'(J\xff\xff\xff\xffJ0\x0b\x01\x00K\x00tR'
            b'U\x17_FixedOffset__dstoffsetN'
            b'U\x12_FixedOffset__nameU\x06cookieubtR.',

            b'\x80\x02cdatetime\ntime\nU\x06\x05\x06\x07\x01\xe2@'
            b'ctest.datetimetester\nPicklableFixedOffset\n)R'
            b'}(U\x14_FixedOffset__offsetcdatetime\ntimedelta\n'
            b'J\xff\xff\xff\xffJ0\x0b\x01\x00K\x00\x87R'
            b'U\x17_FixedOffset__dstoffsetN'
            b'U\x12_FixedOffset__nameU\x06cookieub\x86R.',
        ]

        tinfo = PicklableFixedOffset(-300, 'cookie')
        expected = self.theclass(5, 6, 7, 123456, tzinfo=tinfo)
        for data in tests:
            for loads in pickle_loads:
                derived = loads(data, encoding='latin1')
                self.assertEqual(derived, expected, repr(data))
                self.assertIsInstance(derived.tzinfo, PicklableFixedOffset)
                self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
                self.assertEqual(derived.tzname(), 'cookie') 
Example 72
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_replace(self):
        cls = self.theclass
        z100 = FixedOffset(100, "+100")
        zm200 = FixedOffset(timedelta(minutes=-200), "-200")
        args = [1, 2, 3, 4, z100]
        base = cls(*args)
        self.assertEqual(base, base.replace())

        i = 0
        for name, newval in (("hour", 5),
                             ("minute", 6),
                             ("second", 7),
                             ("microsecond", 8),
                             ("tzinfo", zm200)):
            newargs = args[:]
            newargs[i] = newval
            expected = cls(*newargs)
            got = base.replace(**{name: newval})
            self.assertEqual(expected, got)
            i += 1

        # Ensure we can get rid of a tzinfo.
        self.assertEqual(base.tzname(), "+100")
        base2 = base.replace(tzinfo=None)
        self.assertIsNone(base2.tzinfo)
        self.assertIsNone(base2.tzname())

        # Ensure we can add one.
        base3 = base2.replace(tzinfo=z100)
        self.assertEqual(base, base3)
        self.assertIs(base.tzinfo, base3.tzinfo)

        # Out of bounds.
        base = cls(1)
        self.assertRaises(ValueError, base.replace, hour=24)
        self.assertRaises(ValueError, base.replace, minute=-1)
        self.assertRaises(ValueError, base.replace, second=100)
        self.assertRaises(ValueError, base.replace, microsecond=1000000) 
Example 73
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_compat_unpickle(self):
        tests = [
            b'cdatetime\ndatetime\n'
            b"(S'\\x07\\xdf\\x0b\\x1b\\x14;\\x01\\x01\\xe2@'\n"
            b'ctest.datetimetester\nPicklableFixedOffset\n(tR'
            b"(dS'_FixedOffset__offset'\ncdatetime\ntimedelta\n"
            b'(I-1\nI68400\nI0\ntRs'
            b"S'_FixedOffset__dstoffset'\nNs"
            b"S'_FixedOffset__name'\nS'cookie'\nsbtR.",

            b'cdatetime\ndatetime\n'
            b'(U\n\x07\xdf\x0b\x1b\x14;\x01\x01\xe2@'
            b'ctest.datetimetester\nPicklableFixedOffset\n)R'
            b'}(U\x14_FixedOffset__offsetcdatetime\ntimedelta\n'
            b'(J\xff\xff\xff\xffJ0\x0b\x01\x00K\x00tR'
            b'U\x17_FixedOffset__dstoffsetN'
            b'U\x12_FixedOffset__nameU\x06cookieubtR.',

            b'\x80\x02cdatetime\ndatetime\n'
            b'U\n\x07\xdf\x0b\x1b\x14;\x01\x01\xe2@'
            b'ctest.datetimetester\nPicklableFixedOffset\n)R'
            b'}(U\x14_FixedOffset__offsetcdatetime\ntimedelta\n'
            b'J\xff\xff\xff\xffJ0\x0b\x01\x00K\x00\x87R'
            b'U\x17_FixedOffset__dstoffsetN'
            b'U\x12_FixedOffset__nameU\x06cookieub\x86R.',
        ]
        args = 2015, 11, 27, 20, 59, 1, 123456
        tinfo = PicklableFixedOffset(-300, 'cookie')
        expected = self.theclass(*args, **{'tzinfo': tinfo})
        for data in tests:
            for loads in pickle_loads:
                derived = loads(data, encoding='latin1')
                self.assertEqual(derived, expected)
                self.assertIsInstance(derived.tzinfo, PicklableFixedOffset)
                self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
                self.assertEqual(derived.tzname(), 'cookie') 
Example 74
Project: Old-school-processing   Author: cianfrocco-lab   File: tiltfile.py    MIT License 4 votes vote down vote up
def readData(filename, filetype=None):
	"""
	savedata = {}
	savedata['theta'] = self.data['theta']
	savedata['gamma'] = self.data['gamma']
	savedata['phi'] = self.data['phi']
	savedata['shiftx'] = self.data['shiftx']
	savedata['shifty'] = self.data['shifty']
	savedata['savetime'] = time.asctime()+" "+time.tzname[time.daylight]
	savedata['filetype'] = tiltfile.filetypes[self.data['filetypeindex']]
	savedata['picks1'] = self.getArray1()
	savedata['picks2'] = self.getArray2()
	savedata['align1'] = self.getAlignedArray1()
	savedata['align2'] = self.getAlignedArray2()
	savedata['rmsd'] = self.getRmsdArray()
	savedata['filepath'] = os.path.join(self.data['dirname'], self.data['outfile'])
	savedata['image1name'] = self.panel1.filename
	savedata['image2name'] = self.panel2.filename
	"""
	if not os.path.isfile(filename):
		apDisplay.printWarning("file "+filename+" does not exist")
		return None

	if filetype is None:
		filetype = guessFileType(filename)

	if filetype == 'text':
		savedata = readFromTextFile(filename)
	elif filetype == 'xml':
		savedata = readFromXMLFile(filename)
	elif filetype == 'spider':
		savedata = readFromSpiderFile(filename)
	elif filetype == 'pickle':
		savedata = readFromPickleFile(filename)
	else:
		apDisplay.printWarning("unknown file type")
		return None

	savedata['filename'] = os.path.basename(filename)
	savedata['loadtime'] = time.asctime()+" "+time.tzname[time.daylight]
	savedata['shiftx'] = 0.0
	savedata['shifty'] = 0.0
	savedata['scale'] = 1.0
	return savedata

#--------------------------------------- 
Example 75
Project: ngo-addons-backport   Author: camptocamp   File: misc.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def detect_server_timezone():
    """Attempt to detect the timezone to use on the server side.
       Defaults to UTC if no working timezone can be found.
       @return the timezone identifier as expected by pytz.timezone.
    """
    try:
        import pytz
    except Exception:
        _logger.warning("Python pytz module is not available. "
            "Timezone will be set to UTC by default.")
        return 'UTC'

    # Option 1: the configuration option (did not exist before, so no backwards compatibility issue)
    # Option 2: to be backwards compatible with 5.0 or earlier, the value from time.tzname[0], but only if it is known to pytz
    # Option 3: the environment variable TZ
    sources = [ (config['timezone'], 'OpenERP configuration'),
                (time.tzname[0], 'time.tzname'),
                (os.environ.get('TZ',False),'TZ environment variable'), ]
    # Option 4: OS-specific: /etc/timezone on Unix
    if os.path.exists("/etc/timezone"):
        tz_value = False
        try:
            f = open("/etc/timezone")
            tz_value = f.read(128).strip()
        except Exception:
            pass
        finally:
            f.close()
        sources.append((tz_value,"/etc/timezone file"))
    # Option 5: timezone info from registry on Win32
    if sys.platform == "win32":
        # Timezone info is stored in windows registry.
        # However this is not likely to work very well as the standard name
        # of timezones in windows is rarely something that is known to pytz.
        # But that's ok, it is always possible to use a config option to set
        # it explicitly.
        sources.append((get_win32_timezone(),"Windows Registry"))

    for (value,source) in sources:
        if value:
            try:
                tz = pytz.timezone(value)
                _logger.info("Using timezone %s obtained from %s.", tz.zone, source)
                return value
            except pytz.UnknownTimeZoneError:
                _logger.warning("The timezone specified in %s (%s) is invalid, ignoring it.", source, value)

    _logger.warning("No valid timezone could be detected, using default UTC "
        "timezone. You can specify it explicitly with option 'timezone' in "
        "the server configuration.")
    return 'UTC' 
Example 76
Project: jawfish   Author: war-and-code   File: datetime.py    MIT License 4 votes vote down vote up
def _wrap_strftime(object, format, timetuple):
    # Don't call utcoffset() or tzname() unless actually needed.
    freplace = None # the string to use for %f
    zreplace = None # the string to use for %z
    Zreplace = None # the string to use for %Z

    # Scan format for %z and %Z escapes, replacing as needed.
    newformat = []
    push = newformat.append
    i, n = 0, len(format)
    while i < n:
        ch = format[i]
        i += 1
        if ch == '%':
            if i < n:
                ch = format[i]
                i += 1
                if ch == 'f':
                    if freplace is None:
                        freplace = '%06d' % getattr(object,
                                                    'microsecond', 0)
                    newformat.append(freplace)
                elif ch == 'z':
                    if zreplace is None:
                        zreplace = ""
                        if hasattr(object, "utcoffset"):
                            offset = object.utcoffset()
                            if offset is not None:
                                sign = '+'
                                if offset.days < 0:
                                    offset = -offset
                                    sign = '-'
                                h, m = divmod(offset, timedelta(hours=1))
                                assert not m % timedelta(minutes=1), "whole minute"
                                m //= timedelta(minutes=1)
                                zreplace = '%c%02d%02d' % (sign, h, m)
                    assert '%' not in zreplace
                    newformat.append(zreplace)
                elif ch == 'Z':
                    if Zreplace is None:
                        Zreplace = ""
                        if hasattr(object, "tzname"):
                            s = object.tzname()
                            if s is not None:
                                # strftime is going to have at this: escape %
                                Zreplace = s.replace('%', '%%')
                    newformat.append(Zreplace)
                else:
                    push('%')
                    push(ch)
            else:
                push('%')
        else:
            push(ch)
    newformat = "".join(newformat)
    return _time.strftime(newformat, timetuple) 
Example 77
Project: jawfish   Author: war-and-code   File: datetime.py    MIT License 4 votes vote down vote up
def astimezone(self, tz=None):
        if tz is None:
            if self.tzinfo is None:
                raise ValueError("astimezone() requires an aware datetime")
            ts = (self - _EPOCH) // timedelta(seconds=1)
            localtm = _time.localtime(ts)
            local = datetime(*localtm[:6])
            try:
                # Extract TZ data if available
                gmtoff = localtm.tm_gmtoff
                zone = localtm.tm_zone
            except AttributeError:
                # Compute UTC offset and compare with the value implied
                # by tm_isdst.  If the values match, use the zone name
                # implied by tm_isdst.
                delta = local - datetime(*_time.gmtime(ts)[:6])
                dst = _time.daylight and localtm.tm_isdst > 0
                gmtoff = -(_time.altzone if dst else _time.timezone)
                if delta == timedelta(seconds=gmtoff):
                    tz = timezone(delta, _time.tzname[dst])
                else:
                    tz = timezone(delta)
            else:
                tz = timezone(timedelta(seconds=gmtoff), zone)

        elif not isinstance(tz, tzinfo):
            raise TypeError("tz argument must be an instance of tzinfo")

        mytz = self.tzinfo
        if mytz is None:
            raise ValueError("astimezone() requires an aware datetime")

        if tz is mytz:
            return self

        # Convert self to UTC, and attach the new time zone object.
        myoffset = self.utcoffset()
        if myoffset is None:
            raise ValueError("astimezone() requires an aware datetime")
        utc = (self - myoffset).replace(tzinfo=tz)

        # Convert from UTC to tz's local time.
        return tz.fromutc(utc)

    # Ways to produce a string. 
Example 78
Project: Repobot   Author: Desgard   File: datetime.py    MIT License 4 votes vote down vote up
def _wrap_strftime(object, format, timetuple):
    # Don't call utcoffset() or tzname() unless actually needed.
    freplace = None # the string to use for %f
    zreplace = None # the string to use for %z
    Zreplace = None # the string to use for %Z

    # Scan format for %z and %Z escapes, replacing as needed.
    newformat = []
    push = newformat.append
    i, n = 0, len(format)
    while i < n:
        ch = format[i]
        i += 1
        if ch == '%':
            if i < n:
                ch = format[i]
                i += 1
                if ch == 'f':
                    if freplace is None:
                        freplace = '%06d' % getattr(object,
                                                    'microsecond', 0)
                    newformat.append(freplace)
                elif ch == 'z':
                    if zreplace is None:
                        zreplace = ""
                        if hasattr(object, "utcoffset"):
                            offset = object.utcoffset()
                            if offset is not None:
                                sign = '+'
                                if offset.days < 0:
                                    offset = -offset
                                    sign = '-'
                                h, m = divmod(offset, timedelta(hours=1))
                                assert not m % timedelta(minutes=1), "whole minute"
                                m //= timedelta(minutes=1)
                                zreplace = '%c%02d%02d' % (sign, h, m)
                    assert '%' not in zreplace
                    newformat.append(zreplace)
                elif ch == 'Z':
                    if Zreplace is None:
                        Zreplace = ""
                        if hasattr(object, "tzname"):
                            s = object.tzname()
                            if s is not None:
                                # strftime is going to have at this: escape %
                                Zreplace = s.replace('%', '%%')
                    newformat.append(Zreplace)
                else:
                    push('%')
                    push(ch)
            else:
                push('%')
        else:
            push(ch)
    newformat = "".join(newformat)
    return _time.strftime(newformat, timetuple) 
Example 79
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 4 votes vote down vote up
def test_strptime(self):
        string = '2004-12-01 13:02:47.197'
        format = '%Y-%m-%d %H:%M:%S.%f'
        expected = _strptime._strptime_datetime(self.theclass, string, format)
        got = self.theclass.strptime(string, format)
        self.assertEqual(expected, got)
        self.assertIs(type(expected), self.theclass)
        self.assertIs(type(got), self.theclass)

        # bpo-34482: Check that surrogates are handled properly.
        inputs = [
            ('2004-12-01\ud80013:02:47.197', '%Y-%m-%d\ud800%H:%M:%S.%f'),
            ('2004\ud80012-01 13:02:47.197', '%Y\ud800%m-%d %H:%M:%S.%f'),
            ('2004-12-01 13:02\ud80047.197', '%Y-%m-%d %H:%M\ud800%S.%f'),
        ]
        for string, format in inputs:
            with self.subTest(string=string, format=format):
                expected = _strptime._strptime_datetime(self.theclass, string,
                                                        format)
                got = self.theclass.strptime(string, format)
                self.assertEqual(expected, got)

        strptime = self.theclass.strptime
        self.assertEqual(strptime("+0002", "%z").utcoffset(), 2 * MINUTE)
        self.assertEqual(strptime("-0002", "%z").utcoffset(), -2 * MINUTE)
        self.assertEqual(
            strptime("-00:02:01.000003", "%z").utcoffset(),
            -timedelta(minutes=2, seconds=1, microseconds=3)
        )
        # Only local timezone and UTC are supported
        for tzseconds, tzname in ((0, 'UTC'), (0, 'GMT'),
                                 (-_time.timezone, _time.tzname[0])):
            if tzseconds < 0:
                sign = '-'
                seconds = -tzseconds
            else:
                sign ='+'
                seconds = tzseconds
            hours, minutes = divmod(seconds//60, 60)
            dtstr = "{}{:02d}{:02d} {}".format(sign, hours, minutes, tzname)
            dt = strptime(dtstr, "%z %Z")
            self.assertEqual(dt.utcoffset(), timedelta(seconds=tzseconds))
            self.assertEqual(dt.tzname(), tzname)
        # Can produce inconsistent datetime
        dtstr, fmt = "+1234 UTC", "%z %Z"
        dt = strptime(dtstr, fmt)
        self.assertEqual(dt.utcoffset(), 12 * HOUR + 34 * MINUTE)
        self.assertEqual(dt.tzname(), 'UTC')
        # yet will roundtrip
        self.assertEqual(dt.strftime(fmt), dtstr)

        # Produce naive datetime if no %z is provided
        self.assertEqual(strptime("UTC", "%Z").tzinfo, None)

        with self.assertRaises(ValueError): strptime("-2400", "%z")
        with self.assertRaises(ValueError): strptime("-000", "%z") 
Example 80
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 4 votes vote down vote up
def test_tzinfo_classes(self):
        cls = self.theclass
        class C1(tzinfo):
            def utcoffset(self, dt): return None
            def dst(self, dt): return None
            def tzname(self, dt): return None
        for t in (cls(1, 1, 1),
                  cls(1, 1, 1, tzinfo=None),
                  cls(1, 1, 1, tzinfo=C1())):
            self.assertIsNone(t.utcoffset())
            self.assertIsNone(t.dst())
            self.assertIsNone(t.tzname())

        class C3(tzinfo):
            def utcoffset(self, dt): return timedelta(minutes=-1439)
            def dst(self, dt): return timedelta(minutes=1439)
            def tzname(self, dt): return "aname"
        t = cls(1, 1, 1, tzinfo=C3())
        self.assertEqual(t.utcoffset(), timedelta(minutes=-1439))
        self.assertEqual(t.dst(), timedelta(minutes=1439))
        self.assertEqual(t.tzname(), "aname")

        # Wrong types.
        class C4(tzinfo):
            def utcoffset(self, dt): return "aname"
            def dst(self, dt): return 7
            def tzname(self, dt): return 0
        t = cls(1, 1, 1, tzinfo=C4())
        self.assertRaises(TypeError, t.utcoffset)
        self.assertRaises(TypeError, t.dst)
        self.assertRaises(TypeError, t.tzname)

        # Offset out of range.
        class C6(tzinfo):
            def utcoffset(self, dt): return timedelta(hours=-24)
            def dst(self, dt): return timedelta(hours=24)
        t = cls(1, 1, 1, tzinfo=C6())
        self.assertRaises(ValueError, t.utcoffset)
        self.assertRaises(ValueError, t.dst)

        # Not a whole number of seconds.
        class C7(tzinfo):
            def utcoffset(self, dt): return timedelta(microseconds=61)
            def dst(self, dt): return timedelta(microseconds=-81)
        t = cls(1, 1, 1, tzinfo=C7())
        self.assertEqual(t.utcoffset(), timedelta(microseconds=61))
        self.assertEqual(t.dst(), timedelta(microseconds=-81))