python类altzone()的实例源码

imaplib2.py 文件源码 项目:sndlatr 作者: Schibum 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)))
cmdline.py 文件源码 项目:twittershade 作者: nicolavic98 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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 ""
pkcs7_models.py 文件源码 项目:public_drown_scanner 作者: nimia 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
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
general.py 文件源码 项目:crime-analysis-toolbox 作者: Esri 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
#----------------------------------------------------------------------
imaplib2.py 文件源码 项目:ServerToolkit 作者: ianjjohnson 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
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)))
DateTimeRange.py 文件源码 项目:TranskribusPyClient 作者: Transkribus 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def getTimeZone(cls):
        #The line below is wrong on Nov7th in France, but was corret before the daylight change...
        #I do not understand the documentation, it seems... :-/
        #nbSecWest = time.altzone

        #fix, which I hope works also in summer time... :-O
        t0 = time.time()
        nbSecGMT  = time.mktime(time.gmtime   (t0))
        nbSecHere = time.mktime(time.localtime(t0))
        nbSecWest = nbSecGMT - nbSecHere 

        h, m = int(nbSecWest/3600), nbSecWest % 3600
        if h > 0:
            return "-%02d%02d"%( h,m)
        else:
            return "+%02d%02d"%(-h,m)
Time.py 文件源码 项目:rdiff-backup 作者: sol1 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
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)
cmdline.py 文件源码 项目:TwiBot 作者: ShruthiChari 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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 ""
cmdline.py 文件源码 项目:TwiBot 作者: ShruthiChari 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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 ""
http_server.py 文件源码 项目:ZServer 作者: zopefoundation 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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.
trigger.py 文件源码 项目:siemstress 作者: dogoncouch 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def watch_rule(self):
        """Watch a trigger rule"""

        # Set time zone:
        if daylight:
            self.tzone = \
                    str(int(float(altzone) / 60 // 60)).rjust(2,
                            '0') + \
                    str(int(float(altzone) / 60 % 60)).ljust(2, '0')
        else:
            self.tzone = \
                    str(int(float(timezone) / 60 // 60)).rjust(2,
                            '0') + \
                    str(int(float(timezone) / 60 % 60)).ljust(2, '0')
        if not '-' in self.tzone:
            self.tzone = '+' + self.tzone

        while True:

            # Check the rule:
            self.check_rule()

            # Wait until the next interval
            sleep(int(self.rule['time_int']) * 60)
imaplib.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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) + '"'
imaplib2.py 文件源码 项目:sndlatr 作者: Schibum 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
fixed_offset.py 文件源码 项目:sndlatr 作者: Schibum 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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)
timezone.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
log.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
smtp.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def rfc822date(timeinfo=None,local=1):
    """
    Format an RFC-2822 compliant date string.

    @param timeinfo: (optional) A sequence as returned by C{time.localtime()}
        or C{time.gmtime()}. Default is now.
    @param local: (optional) Indicates if the supplied time is local or
        universal time, or if no time is given, whether now should be local or
        universal time. Default is local, as suggested (SHOULD) by rfc-2822.

    @returns: A string representing the time and date in RFC-2822 format.
    """
    if not timeinfo:
        if local:
            timeinfo = time.localtime()
        else:
            timeinfo = time.gmtime()
    if local:
        if timeinfo[8]:
            # DST
            tz = -time.altzone
        else:
            tz = -time.timezone

        (tzhr, tzmin) = divmod(abs(tz), 3600)
        if tz:
            tzhr *= int(abs(tz)/tz)
        (tzmin, tzsec) = divmod(tzmin, 60)
    else:
        (tzhr, tzmin) = (0,0)

    return "%s, %02d %s %04d %02d:%02d:%02d %+03d%02d" % (
        ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][timeinfo[6]],
        timeinfo[2],
        ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
         'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][timeinfo[1] - 1],
        timeinfo[0], timeinfo[3], timeinfo[4], timeinfo[5],
        tzhr, tzmin)
imaplib.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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) + '"'
TCtimes.py 文件源码 项目:vspheretools 作者: devopshq 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
tz.py 文件源码 项目:aws-cfn-plex 作者: lordmuffin 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
log.py 文件源码 项目:Taigabot 作者: FrozenPigs 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def time(self):
        """time as tuple:

        * [0] = int(time)
        * [1] = int(timezone_offset) in time.altzone format """
        return self[3]
log.py 文件源码 项目:Taigabot 作者: FrozenPigs 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def append_entry(cls, config_reader, filepath, oldbinsha, newbinsha, message):
        """Append a new log entry to the revlog at filepath.

        :param config_reader: configuration reader of the repository - used to obtain
            user information. May also be an Actor instance identifying the committer directly.
            May also be None
        :param filepath: full path to the log file
        :param oldbinsha: binary sha of the previous commit
        :param newbinsha: binary sha of the current commit
        :param message: message describing the change to the reference
        :param write: If True, the changes will be written right away. Otherwise
            the change will not be written
        :return: RefLogEntry objects which was appended to the log
        :note: As we are append-only, concurrent access is not a problem as we
            do not interfere with readers."""
        if len(oldbinsha) != 20 or len(newbinsha) != 20:
            raise ValueError("Shas need to be given in binary format")
        # END handle sha type
        assure_directory_exists(filepath, is_file=True)
        first_line = message.split('\n')[0]
        committer = isinstance(config_reader, Actor) and config_reader or Actor.committer(config_reader)
        entry = RefLogEntry((
            bin_to_hex(oldbinsha).decode('ascii'),
            bin_to_hex(newbinsha).decode('ascii'),
            committer, (int(time.time()), time.altzone), first_line
        ))

        lf = LockFile(filepath)
        lf._obtain_lock_or_raise()
        fd = open(filepath, 'ab')
        try:
            fd.write(entry.format().encode(defenc))
        finally:
            fd.close()
            lf._release_lock()
        # END handle write operation

        return entry
util.py 文件源码 项目:Taigabot 作者: FrozenPigs 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def utctz_to_altz(utctz):
    """we convert utctz to the timezone in seconds, it is the format time.altzone
    returns. Git stores it as UTC timezone which has the opposite sign as well,
    which explains the -1 * ( that was made explicit here )
    :param utctz: git utc timezone string, i.e. +0200"""
    return -1 * int(float(utctz) / 100 * 3600)
tz.py 文件源码 项目:AshsSDK 作者: thehappydinoa 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
gateways.py 文件源码 项目:bitmask-dev 作者: leapcode 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:hakkuframework 作者: 4shadoww 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
SmoothUtils.py 文件源码 项目:SSTV-PLEX-PLUGIN 作者: vorghahn 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)
tz.py 文件源码 项目:oa_qian 作者: sunqb 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
test_utils.py 文件源码 项目:supvisors 作者: julien6387 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_localtime(self):
        """ Test the display of local time. """
        import time
        from supvisors.utils import simple_localtime
        time_shift = time.timezone if time.gmtime().tm_isdst else time.altzone
        self.assertEqual('07:07:00', simple_localtime(1476947220.416198 + time_shift))


问题


面经


文章

微信
公众号

扫码关注公众号