當前位置: 首頁>>代碼示例>>Python>>正文


Python time.localtime方法代碼示例

本文整理匯總了Python中time.localtime方法的典型用法代碼示例。如果您正苦於以下問題:Python time.localtime方法的具體用法?Python time.localtime怎麽用?Python time.localtime使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在time的用法示例。


在下文中一共展示了time.localtime方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: create_time_table

# 需要導入模塊: import time [as 別名]
# 或者: from time import localtime [as 別名]
def create_time_table(self, t):
        t = time.localtime(t)
        hr = t.tm_hour
        if not self.mil_time:
            hr = hr % 12
        hrs = str(hr).zfill(2)
        mins = str(t.tm_min).zfill(2)
        val = hrs + ":" + mins
        w, h = font.str_dim(val, font=self.font_name,
                            font_scale=self.scale, final_sep=False)
        x = (self.width - w) // 2
        y = (self.height - h) // 2
        old_buf = copy.copy(self.layout.colors)
        self.layout.all_off()
        self.layout.drawText(val, x, y, color=COLORS.Red,
                             font=self.font_name, font_scale=self.scale)
        table = []
        for y in range(self.height):
            table.append([0] * self.width)
            for x in range(self.width):
                table[y][x] = int(any(self.layout.get(x, y)))
        self.layout.setBuffer(old_buf)
        return table 
開發者ID:ManiacalLabs,項目名稱:BiblioPixelAnimations,代碼行數:25,代碼來源:GameOfLife.py

示例2: getFileNameList

# 需要導入模塊: import time [as 別名]
# 或者: from time import localtime [as 別名]
def getFileNameList():
    currentDate = time.strftime("%Y/%m/%d", time.localtime())
    fileNameList = []
    start_time_epoch = long(time.time())
    chunks = int(reportingConfigVars['reporting_interval'] / 5)
    startMin = time.strftime("%Y%m%d%H%M", time.localtime(start_time_epoch))
    closestMinute = closestNumber(int(startMin[-2:]), 5)
    if closestMinute < 10:
        closestMinStr = '0' + str(closestMinute)
        newDate = startMin[:-2] + str(closestMinStr)
    else:
        newDate = startMin[:-2] + str(closestMinute)
    chunks -= 1
    currentTime = datetime.datetime.strptime(newDate, "%Y%m%d%H%M") - datetime.timedelta(minutes=5)
    closestMinute = time.strftime("%Y%m%d%H%M", currentTime.timetuple())
    filename = os.path.join(currentDate, "nfcapd." + closestMinute)
    fileNameList.append(filename)
    while chunks >= 0:
        chunks -= 1
        currentTime = datetime.datetime.strptime(closestMinute, "%Y%m%d%H%M") - datetime.timedelta(minutes=5)
        closestMinute = time.strftime("%Y%m%d%H%M", currentTime.timetuple())
        filename = os.path.join(currentDate, "nfcapd." + closestMinute)
        fileNameList.append(filename)

    return set(fileNameList) - getLastSentFiles() 
開發者ID:insightfinder,項目名稱:InsightAgent,代碼行數:27,代碼來源:getmetrics_nfdump.py

示例3: __init__

# 需要導入模塊: import time [as 別名]
# 或者: from time import localtime [as 別名]
def __init__(self,lexer=None):
        if lexer is None:
            lexer = lex.lexer
        self.lexer = lexer
        self.macros = { }
        self.path = []
        self.temp_path = []

        # Probe the lexer for selected tokens
        self.lexprobe()

        tm = time.localtime()
        self.define("__DATE__ \"%s\"" % time.strftime("%b %d %Y",tm))
        self.define("__TIME__ \"%s\"" % time.strftime("%H:%M:%S",tm))
        self.parser = None

    # -----------------------------------------------------------------------------
    # tokenize()
    #
    # Utility function. Given a string of text, tokenize into a list of tokens
    # ----------------------------------------------------------------------------- 
開發者ID:nojanath,項目名稱:SublimeKSP,代碼行數:23,代碼來源:cpp.py

示例4: createBuiltinDefines

# 需要導入模塊: import time [as 別名]
# 或者: from time import localtime [as 別名]
def createBuiltinDefines(lines):
	# Create date-time variables

	timecodes = ['%S', '%M', '%H', '%I', '%p', '%d', '%m', '%Y', '%y', '%B', '%b', '%x', '%X']
	timenames = ['__SEC__','__MIN__','__HOUR__','__HOUR12__','__AMPM__','__DAY__','__MONTH__','__YEAR__','__YEAR2__','__LOCALE_MONTH__','__LOCALE_MONTH_ABBR__','__LOCALE_DATE__','__LOCALE_TIME__']
	defines = ['define {0} := \"{1}\"'.format(timenames[i], strftime(timecodes[i], localtime())) for i in range(len(timecodes))]

	newLines = collections.deque()

	# append our defines on top of the script in a temporary deque
	for string in defines:
		newLines.append(lines[0].copy(string))

	# merge with the original unmodified script
	for line in lines:
		newLines.append(line)

	# replace original deque with modified one
	replaceLines(lines, newLines)

#================================================================================================= 
開發者ID:nojanath,項目名稱:SublimeKSP,代碼行數:23,代碼來源:preprocessor_plugins.py

示例5: add_status

# 需要導入模塊: import time [as 別名]
# 或者: from time import localtime [as 別名]
def add_status(self, pgrid_w, eday_kwh, temperature, voltage):
        t = time.localtime()
        payload = {
            'd' : "{:04}{:02}{:02}".format(t.tm_year, t.tm_mon, t.tm_mday),
            't' : "{:02}:{:02}".format(t.tm_hour, t.tm_min),
            'v1' : round(eday_kwh * 1000),
            'v2' : round(pgrid_w)
        }

        if temperature is not None:
            payload['v5'] = temperature

        if voltage is not None:
            payload['v6'] = voltage

        self.call("https://pvoutput.org/service/r2/addstatus.jsp", payload) 
開發者ID:markruys,項目名稱:gw2pvo,代碼行數:18,代碼來源:pvo_api.py

示例6: __init__

# 需要導入模塊: import time [as 別名]
# 或者: from time import localtime [as 別名]
def __init__(self):
    self.currenttime = time.localtime()
    printtime = time.strftime("%Y%m%d%H%M%S ", self.currenttime)
    self.logfile = open(config['files']['logfile'],'at',buffering=1)
    self.sampletime = time.time()
    self.prevtime = time.localtime()
    self.summary=loadsummary()

#      summary = open('/media/75cc9171-4331-4f88-ac3f-0278d132fae9/summary','w')
#      pickle.dump(hivolts, summary)
#      pickle.dump(lowvolts, summary)
#      summary.close()
    if self.summary['hour']['timestamp'][0:10] != printtime[0:10]:
      self.summary['hour'] = deepcopy(self.summary['current'])
    if self.summary['currentday']['timestamp'][0:8] != printtime[0:8]:
      self.summary['currentday'] = deepcopy(self.summary['current'])
    if self.summary['monthtodate']['timestamp'][0:6] != printtime[0:6]:
      self.summary['monthtodate'] = deepcopy(self.summary['current'])
    if self.summary['yeartodate']['timestamp'][0:4] != printtime[0:4]:
      self.summary['yeartodate'] = deepcopy(self.summary['current']) 
開發者ID:simat,項目名稱:BatteryMonitor,代碼行數:22,代碼來源:summary.py

示例7: scanalarms

# 需要導入模塊: import time [as 別名]
# 或者: from time import localtime [as 別名]
def scanalarms(self,batdata):
#    self.timedate = localtime()
#    print (self.timedate.tm_hour)
    for i in config['alarms']:
      if not self.alarmtriggered[i]:
        exec(config['alarms'][i][1])
  #      log.debug('{}{}{}'.format(self.test,batdata.maxcellv,batdata.lastmaxcellv))
        if self.test:
    #            sys.stderr.write('Alarm 1 triggered')
          log.info('alarm {} triggered'.format(i))
          self.alarmtriggered[i]=True
          exec(config['alarms'][i][2])

      if self.alarmtriggered[i]:
        exec(config['alarms'][i][3])
        if self.test:
          log.info('alarm {} reset'.format(i))
          self.alarmtriggered[i]=False
          exec(config['alarms'][i][4]) 
開發者ID:simat,項目名稱:BatteryMonitor,代碼行數:21,代碼來源:alarms.py

示例8: getbmsdat

# 需要導入模塊: import time [as 別名]
# 或者: from time import localtime [as 別名]
def getbmsdat(self,port,command):
    """ Issue BMS command and return data as byte data """
    """ assumes data port is open and configured """
    for i in range(5):
      try:
        port.write(command)
        reply = port.read(4)
#        raise serial.serialutil.SerialException('hithere')
        break
      except serial.serialutil.SerialException as err:
        errfile=open(config['files']['errfile'],'at')
        errfile.write(time.strftime("%Y%m%d%H%M%S ", time.localtime())+str(err.args)+'\n')
        errfile.close()

  #  print (reply)
    x = int.from_bytes(reply[3:5], byteorder = 'big')
#    print (x)
    data = port.read(x)
    end = port.read(3)
#    print (data)
    return data 
開發者ID:simat,項目名稱:BatteryMonitor,代碼行數:23,代碼來源:getbms.py

示例9: clock

# 需要導入模塊: import time [as 別名]
# 或者: from time import localtime [as 別名]
def clock(self, military_time):
        """Clock script modified from:
            https://github.com/johnlr/raspberrypi-tm1637"""
        self.ShowDoublepoint(True)
        while (not self.__stop_event.is_set()):
            t = localtime()
            hour = t.tm_hour
            if not military_time:
                hour = 12 if (t.tm_hour % 12) == 0 else t.tm_hour % 12
            d0 = hour // 10 if hour // 10 else 0
            d1 = hour % 10
            d2 = t.tm_min // 10
            d3 = t.tm_min % 10
            digits = [d0, d1, d2, d3]
            self.Show(digits)
            # # Optional visual feedback of running alarm:
            # print digits
            # for i in tqdm(range(60 - t.tm_sec)):
            for i in range(60 - t.tm_sec):
                if (not self.__stop_event.is_set()):
                    sleep(1) 
開發者ID:timwaizenegger,項目名稱:raspberrypi-examples,代碼行數:23,代碼來源:tm1637.py

示例10: logmsg

# 需要導入模塊: import time [as 別名]
# 或者: from time import localtime [as 別名]
def logmsg(request,type,message,args):
    is_dst = time.daylight and time.localtime().tm_isdst > 0
    tz =  - (time.altzone if is_dst else time.timezone) / 36
    if tz>=0:
        tz="+%04d"%tz
    else:
        tz="%05d"%tz
    datestr = '%d/%b/%Y %H:%M:%S'
    user = getattr(logStore,'user','')
    isValid = getattr(logStore,'isValid','')
    code = getattr(logStore,'code','')
    args = getLogDateTime(args)
    log = '%s %s,%s,%s,%s,%s,%s' % (datetime.now().strftime(datestr),tz,request.address_string(),user,isValid,code, message % args)
    with logLock:
        with open(cfg.logpath,'a') as fw:
            fw.write(log+os.linesep)
    return log 
開發者ID:CboeSecurity,項目名稱:password_pwncheck,代碼行數:19,代碼來源:password-pwncheck.py

示例11: formatTime

# 需要導入模塊: import time [as 別名]
# 或者: from time import localtime [as 別名]
def formatTime(self, record, datefmt=None):
        """
        Return the creation time of the specified LogRecord as formatted text.

        This method should be called from format() by a formatter which
        wants to make use of a formatted time. This method can be overridden
        in formatters to provide for any specific requirement, but the
        basic behaviour is as follows: if datefmt (a string) is specified,
        it is used with time.strftime() to format the creation time of the
        record. Otherwise, the ISO8601 format is used. The resulting
        string is returned. This function uses a user-configurable function
        to convert the creation time to a tuple. By default, time.localtime()
        is used; to change this for a particular formatter instance, set the
        'converter' attribute to a function with the same signature as
        time.localtime() or time.gmtime(). To change it for all formatters,
        for example if you want all logging times to be shown in GMT,
        set the 'converter' attribute in the Formatter class.
        """
        ct = self.converter(record.created)
        if datefmt:
            s = time.strftime(datefmt, ct)
        else:
            t = time.strftime(self.default_time_format, ct)
            s = self.default_msec_format % (t, record.msecs)
        return s 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:27,代碼來源:__init__.py

示例12: get_ports

# 需要導入模塊: import time [as 別名]
# 或者: from time import localtime [as 別名]
def get_ports(self, ipaddr, ports):
        self.create_ports()
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        for i in ports:
            service = i.get('server')
            port = i.get('port')
            banner = i.get('banner')
            banner = re.sub('<', '', banner)
            banner = re.sub('>', '', banner)
            md5sum = hashlib.md5()
            strings = str(ipaddr) + str(service) + str(port)
            md5sum.update(strings.encode('utf-8'))
            md5 = md5sum.hexdigest()
            values = (timestamp, ipaddr, service, port, banner, md5)
            query = "INSERT OR IGNORE INTO ports (time, ipaddr, service, port, banner,md5) VALUES (?,?,?,?,?,?)"
            self.insert_ports(query, values) 
開發者ID:al0ne,項目名稱:Vxscan,代碼行數:18,代碼來源:sqldb.py

示例13: get_crawl

# 需要導入模塊: import time [as 別名]
# 或者: from time import localtime [as 別名]
def get_crawl(self, domain, crawl):
        self.create_crawl()
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        for i in crawl:
            if 'Dynamic:' in i:
                type = 'Dynamic link'
            else:
                type = 'Leaks'
            md5sum = hashlib.md5()
            try:
                text = re.search(r'(?<=Email: ).*|(?<=Phone: ).*', i).group()
            except:
                text = str(i)
            strings = str(domain) + text
            md5sum.update(strings.encode('utf-8'))
            md5 = md5sum.hexdigest()
            values = (timestamp, domain, type, i, md5)
            query = "INSERT OR IGNORE INTO Crawl (time, domain, type, leaks, md5) VALUES (?,?,?,?,?)"
            self.insert_crawl(query, values)
        self.commit()
        self.close() 
開發者ID:al0ne,項目名稱:Vxscan,代碼行數:23,代碼來源:sqldb.py

示例14: print_log

# 需要導入模塊: import time [as 別名]
# 或者: from time import localtime [as 別名]
def print_log(msg, print_flag = True):
    """

    Parameters
    ----------
    msg
    print_flag

    Returns
    -------

    """
    if print_flag:
        if isinstance(msg, str):
            print('%s | %s' % (time.strftime("%m/%d/%y @ %I:%M %p", time.localtime()), msg))
        else:
            print('%s | %r' % (time.strftime("%m/%d/%y @ %I:%M %p", time.localtime()), msg))
        sys.stdout.flush() 
開發者ID:ustunb,項目名稱:risk-slim,代碼行數:20,代碼來源:helper_functions.py

示例15: collapse_rfc2231_value

# 需要導入模塊: import time [as 別名]
# 或者: from time import localtime [as 別名]
def collapse_rfc2231_value(value, errors='replace',
                           fallback_charset='us-ascii'):
    if not isinstance(value, tuple) or len(value) != 3:
        return unquote(value)
    # While value comes to us as a unicode string, we need it to be a bytes
    # object.  We do not want bytes() normal utf-8 decoder, we want a straight
    # interpretation of the string as character bytes.
    charset, language, text = value
    rawbytes = bytes(text, 'raw-unicode-escape')
    try:
        return str(rawbytes, charset, errors)
    except LookupError:
        # charset is not a known codec.
        return unquote(text)


#
# datetime doesn't provide a localtime function yet, so provide one.  Code
# adapted from the patch in issue 9527.  This may not be perfect, but it is
# better than not having it.
# 
開發者ID:Soft8Soft,項目名稱:verge3d-blender-addon,代碼行數:23,代碼來源:utils.py


注:本文中的time.localtime方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。