我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用time.tzname()。
def date_time_str(t): """Convert seconds since the Epoch to formatted local date and time strings.""" source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH') if source_date_epoch is not None: t = time.gmtime(min(t, int(source_date_epoch))) else: t = time.localtime(t) date_str = time.strftime('%Y-%m-%d',t) time_str = time.strftime('%H:%M:%S',t) if source_date_epoch is not None: time_str += ' UTC' elif time.daylight and t.tm_isdst == 1: time_str += ' ' + time.tzname[1] else: time_str += ' ' + time.tzname[0] # Attempt to convert the localtime to the output encoding. try: time_str = char_encode(time_str.decode(locale.getdefaultlocale()[1])) except Exception: pass return date_str, time_str
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
def test_pickling(self): # Try one without a tzinfo. args = 20, 59, 16, 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) # Try one with a tzinfo. tinfo = PicklableFixedOffset(-300, 'cookie') orig = self.theclass(5, 6, 7, tzinfo=tinfo) 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')
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) # 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')
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")
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"): return 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
def _detect_timezone_php(): tomatch = (time.tzname[0], time.timezone, time.daylight) now = datetime.datetime.now() matches = [] for tzname in pytz.all_timezones: try: tz = pytz.timezone(tzname) except IOError: continue try: indst = tz.localize(now).timetuple()[-1] if tomatch == (tz._tzname, -tz._utcoffset.seconds, indst): matches.append(tzname) # pylint: disable-msg=W0704 except AttributeError: pass if len(matches) > 1: warnings.warn("We detected multiple matches for the timezone, choosing " "the first %s. (Matches where %s)" % (matches[0], matches)) return pytz.timezone(matches[0])
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))
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')
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)
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
def tzname(self, dt): return "UTC"
def tzname(self, dt): return self._name
def tzname(self, dt): return time.tzname[self._isdst(dt)]
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
def tzname(self, dt): if self._isdst(dt): return self._dst_abbr else: return self._std_abbr
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
def tzname(self, dt): return self._find_comp(dt).tzname
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
def tzname(self, dt): return self.__name
def tzname(self, dt): return _time.tzname[self._isdst(dt)]
def tzname(self, dt): if self.dst(dt): return self.dstname else: return self.stdname
def __init__(self, options): config.update_etc(options.configfile) if options.logconf: logging.config.fileConfig(options.logconf) logging.getLogger('server').info('using %s as logging ' 'configuration file', options.logconf) else: logformat = ('%(process)s %(thread)s [%(asctime)s] ' '%(levelname)s %(name)s %(message)s') if options.verbose: if options.dev: level = logging.DEBUG else: level = logging.INFO else: level = logging.ERROR logging.basicConfig(level=level, format=logformat) self.logger = logging.getLogger(__name__) if options.configfile: self.logger.info('using %s as configuration file', options.configfile) else: self.logger.info('using default configuration') self.logger.info('initialising distributed objects services') self.xmlrpcd = [] self.jsonrpcd = [] self.webdavd = [] self.options = options if time.tzname[0] != 'UTC': self.logger.error('timezone is not set to UTC')
def tzname(self, dt): if self._name is not None: return self._name else: seconds = self._offset.seconds + self._offset.days * 86400 hours, seconds = divmod(seconds, 3600) minutes = seconds / 60 if minutes: return "%+03d:%d" % (hours, minutes) else: return "%+03d" % hours
def tzname(self, dt): is_dst = False if dt is None else self._isdst(dt) return _time.tzname[is_dst]
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.
def tzname(self, dt): """datetime -> string name of time zone.""" tt = _localtime(_mktime((dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1))) return _time.tzname[tt.tm_isdst > 0]
def tzname(self, dt): """datetime -> string name of time zone.""" #return self.__name return "server"
def show_zone_info(): print(' TZ :', os.environ.get('TZ', '(not set)')) print(' tzname:', time.tzname) print(' Zone : {} ({})'.format( time.timezone, (time.timezone / 3600))) print(' DST :', time.daylight) print(' Time :', time.ctime()) print()