我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用time.daylight()。
def Time2Internaldate(date_time): """'"DD-Mmm-YYYY HH:MM:SS +HHMM"' = Time2Internaldate(date_time) Convert 'date_time' to IMAP4 INTERNALDATE representation.""" if isinstance(date_time, (int, float)): tt = time.localtime(date_time) elif isinstance(date_time, (tuple, time.struct_time)): tt = date_time elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'): return date_time # Assume in correct format else: raise ValueError("date_time not of a known type") if time.daylight and tt[-1]: zone = -time.altzone else: zone = -time.timezone return ('"%2d-%s-%04d %02d:%02d:%02d %+03d%02d"' % ((tt[2], MonthNames[tt[1]], tt[0]) + tt[3:6] + divmod(zone//60, 60)))
def get_time_string(status, options, format="%a %b %d %H:%M:%S +0000 %Y"): timestamp = options["timestamp"] datestamp = options["datestamp"] t = time.strptime(status['created_at'], format) i_hate_timezones = time.timezone if time.daylight: i_hate_timezones = time.altzone dt = datetime.datetime(*t[:-3]) - datetime.timedelta( seconds=i_hate_timezones) t = dt.timetuple() if timestamp and datestamp: return time.strftime("%Y-%m-%d %H:%M:%S ", t) elif timestamp: return time.strftime("%H:%M:%S ", t) elif datestamp: return time.strftime("%Y-%m-%d ", t) return ""
def get_genTime_as_datetime(self): """ parses the genTime string and returns a datetime object; it also adjusts the time according to local timezone, so that it is compatible with other parts of the library """ year = int(self.genTime[:4]) month = int(self.genTime[4:6]) day = int(self.genTime[6:8]) hour = int(self.genTime[8:10]) minute = int(self.genTime[10:12]) second = int(self.genTime[12:14]) rest = self.genTime[14:].strip("Z") if rest: micro = int(float(rest)*1e6) else: micro = 0 tz_delta = datetime.timedelta(seconds=time.daylight and time.altzone or time.timezone) return datetime.datetime(year, month, day, hour, minute, second, micro) - tz_delta
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 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 __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)
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 local_time_to_online(dt=None): """ converts datetime object to a UTC timestamp for AGOL Inputs: dt - datetime object Output: Long value """ if dt is None: dt = datetime.datetime.now() is_dst = time.daylight and time.localtime().tm_isdst > 0 utc_offset = (time.altzone if is_dst else time.timezone) return (time.mktime(dt.timetuple()) * 1000) + (utc_offset *1000) #----------------------------------------------------------------------
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
def gettzd(timeinseconds = None): """Return w3's timezone identification string. Expresed as [+/-]hh:mm. For instance, PDT is -07:00 during dayling savings and -08:00 otherwise. Zone coincides with what localtime(), etc., use. If no argument given, use the current time. """ if timeinseconds is None: timeinseconds = time.time() dst_in_effect = time.daylight and time.localtime(timeinseconds)[8] if dst_in_effect: offset = -time.altzone/60 else: offset = -time.timezone/60 if offset > 0: prefix = "+" elif offset < 0: prefix = "-" else: return "Z" # time is already in UTC if Globals.use_compatible_timestamps: time_separator = '-' else: time_separator = ':' hours, minutes = map(abs, divmod(offset, 60)) assert 0 <= hours <= 23 assert 0 <= minutes <= 59 return "%s%02d%s%02d" % (prefix, hours, time_separator, minutes)
def get_time_string(status, options, format="%a %b %d %H:%M:%S +0000 %Y"): timestamp = options["timestamp"] datestamp = options["datestamp"] t = time.strptime(status['created_at'], format) i_hate_timezones = time.timezone if (time.daylight): i_hate_timezones = time.altzone dt = datetime.datetime(*t[:-3]) - datetime.timedelta( seconds=i_hate_timezones) t = dt.timetuple() if timestamp and datestamp: return time.strftime("%Y-%m-%d %H:%M:%S ", t) elif timestamp: return time.strftime("%H:%M:%S ", t) elif datestamp: return time.strftime("%Y-%m-%d ", t) return ""
def compute_timezone_for_log(): if time.daylight: tz = time.altzone else: tz = time.timezone if tz > 0: neg = 1 else: neg = 0 tz = -tz h, rem = divmod(tz, 3600) m, rem = divmod(rem, 60) if neg: return '-%02d%02d' % (h, m) else: return '+%02d%02d' % (h, m) # if you run this program over a TZ change boundary, this will be invalid.
def Time2Internaldate(date_time): """Convert date_time to IMAP4 INTERNALDATE representation. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'. The date_time argument can be a number (int or float) representing seconds since epoch (as returned by time.time()), a 9-tuple representing local time (as returned by time.localtime()), or a double-quoted string. In the last case, it is assumed to already be in the correct format. """ if isinstance(date_time, (int, float)): tt = time.localtime(date_time) elif isinstance(date_time, (tuple, time.struct_time)): tt = date_time elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'): return date_time # Assume in correct format else: raise ValueError("date_time not of a known type") dt = time.strftime("%d-%b-%Y %H:%M:%S", tt) if dt[0] == '0': dt = ' ' + dt[1:] if time.daylight and tt[-1]: zone = -time.altzone else: zone = -time.timezone return '"' + dt + " %+03d%02d" % divmod(zone//60, 60) + '"'
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 Internaldate2Time(resp): """time_tuple = Internaldate2Time(resp) Convert IMAP4 INTERNALDATE to UT.""" mo = InternalDate.match(resp) if not mo: return None mon = Mon2num[mo.group('mon')] zonen = mo.group('zonen') day = int(mo.group('day')) year = int(mo.group('year')) hour = int(mo.group('hour')) min = int(mo.group('min')) sec = int(mo.group('sec')) zoneh = int(mo.group('zoneh')) zonem = int(mo.group('zonem')) # INTERNALDATE timezone must be subtracted to get UT zone = (zoneh*60 + zonem)*60 if zonen == '-': zone = -zone tt = (year, mon, day, hour, min, sec, -1, -1, -1) utc = time.mktime(tt) # Following is necessary because the time module has no 'mkgmtime'. # 'mktime' assumes arg in local timezone, so adds timezone/altzone. lt = time.localtime(utc) if time.daylight and lt[-1]: zone = zone + time.altzone else: zone = zone + time.timezone return time.localtime(utc - zone)
def for_system(klass): """Return a FixedOffset instance for the current working timezone and DST conditions. """ if time.localtime().tm_isdst and time.daylight: offset = time.altzone else: offset = time.timezone return klass(-offset // 60)
def __init__(self): self.STDOFFSET = timedelta(seconds=-_time.timezone) if _time.daylight: self.DSTOFFSET = timedelta(seconds=-_time.altzone) else: self.DSTOFFSET = self.STDOFFSET self.DSTDIFF = self.DSTOFFSET - self.STDOFFSET tzinfo.__init__(self)
def getTimezoneOffset(self): """ Return the current local timezone offset from UTC. @rtype: C{int} @return: The number of seconds offset from UTC. West is positive, east is negative. """ if time.daylight: return time.altzone return time.timezone
def __init__(self, *a, **kw): _tzinfo.__init__(self, *a, **kw) self.__dstoffset = self.__stdoffset = _timedelta(seconds=-_time.timezone) if _time.daylight: self.__dstoffset = _timedelta(seconds=-_time.altzone) self.__dstdiff = self.__dstoffset - self.__stdoffset
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()
def __init__(self): super(tzlocal, self).__init__() self._std_offset = datetime.timedelta(seconds=-time.timezone) if time.daylight: self._dst_offset = datetime.timedelta(seconds=-time.altzone) else: self._dst_offset = self._std_offset self._dst_saved = self._dst_offset - self._std_offset self._hasdst = bool(self._dst_saved)
def _get_local_offset(self): ''' Return the distance between GMT and the local timezone. :rtype: int ''' local_offset = time.timezone if time.daylight: local_offset = time.altzone return -local_offset / 3600
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)
def GetDateTimeNative(strTime): try: parser = dateutil.parser() is_dst = time.daylight and time.localtime().tm_isdst > 0 utc_offset = - (time.altzone if is_dst else time.timezone) return (parser.parse(strTime) - datetime.timedelta(hours=Dict['ScheduleUtcOffset'])).replace(tzinfo=dateutil.tz.tzutc()).astimezone(dateutil.tz.tzlocal()) except: Log.Error("GetDateTimeNative " + strTime)
def __init__(self): self._std_offset = datetime.timedelta(seconds=-time.timezone) if time.daylight: self._dst_offset = datetime.timedelta(seconds=-time.altzone) else: self._dst_offset = self._std_offset
def test_data_attributes(self): time.altzone time.daylight time.timezone time.tzname
def test_default_values_for_zero(self): # Make sure that using all zeros uses the proper default values. # No test for daylight savings since strftime() does not change output # based on its value. expected = "2000 01 01 00 00 00 1 001" with support.check_warnings(): result = time.strftime("%Y %m %d %H %M %S %w %j", (0,)*9) self.assertEqual(expected, result)
def test_locale_data_w_regex_metacharacters(self): # Check that if locale data contains regex metacharacters they are # escaped properly. # Discovered by bug #1039270 . locale_time = _strptime.LocaleTime() locale_time.timezone = (frozenset(("utc", "gmt", "Tokyo (standard time)")), frozenset("Tokyo (daylight time)")) time_re = _strptime.TimeRE(locale_time) self.assertTrue(time_re.compile("%Z").match("Tokyo (standard time)"), "locale data that contains regex metacharacters is not" " properly escaped")