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


Python time.strftime方法代碼示例

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


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

示例1: _get_header

# 需要導入模塊: import time [as 別名]
# 或者: from time import strftime [as 別名]
def _get_header(border, game_date, show_scores, show_linescore):
        header = list()
        date_hdr = '{:7}{} {}'.format('', game_date, datetime.strftime(datetime.strptime(game_date, "%Y-%m-%d"), "%a"))
        if show_scores:
            if show_linescore:
                header.append("{:56}".format(date_hdr))
                header.append('{c_on}{dash}{c_off}'
                              .format(c_on=border.border_color, dash=border.thickdash*92, c_off=border.color_off))
            else:
                header.append("{:48} {:^7} {pipe} {:^5} {pipe} {:^9} {pipe} {}"
                              .format(date_hdr, 'Series', 'Score', 'State', 'Feeds', pipe=border.pipe))
                header.append("{c_on}{}{pipe}{}{pipe}{}{pipe}{}{c_off}"
                              .format(border.thickdash * 57, border.thickdash * 7, border.thickdash * 11, border.thickdash * 16,
                                      pipe=border.junction, c_on=border.border_color, c_off=border.color_off))
        else:
            header.append("{:48} {:^7} {pipe} {:^9} {pipe} {}".format(date_hdr, 'Series', 'State', 'Feeds', pipe=border.pipe))
            header.append("{c_on}{}{pipe}{}{pipe}{}{c_off}"
                          .format(border.thickdash * 57, border.thickdash * 11, border.thickdash * 16,
                                  pipe=border.junction, c_on=border.border_color, c_off=border.color_off))
        return header 
開發者ID:kmac,項目名稱:mlbv,代碼行數:22,代碼來源:mlbgamedata.py

示例2: dump_artifacts

# 需要導入模塊: import time [as 別名]
# 或者: from time import strftime [as 別名]
def dump_artifacts(r, injector, command_line):
    global arch
    tee = Tee(LOG, "w")
    tee.write("#\n")
    tee.write("# %s\n" % command_line)
    tee.write("# %s\n" % injector.command)
    tee.write("#\n")
    tee.write("# insn tested: %d\n" % r.ic)
    tee.write("# artf found:  %d\n" % r.ac)
    tee.write("# runtime:     %s\n" % r.elapsed())
    tee.write("# seed:        %d\n" % injector.settings.seed)
    tee.write("# arch:        %s\n" % arch)
    tee.write("# date:        %s\n" % time.strftime("%Y-%m-%d %H:%M:%S"))
    tee.write("#\n")
    tee.write("# cpu:\n")

    cpu = get_cpu_info()
    for l in cpu:
        tee.write("# %s\n" % l) 

    tee.write("# %s  v  l  s  c\n" % (" " * 28))
    for k in sorted(list(r.ad)):
        v = r.ad[k]
        tee.write(result_string(k, v)) 
開發者ID:Battelle,項目名稱:sandsifter,代碼行數:26,代碼來源:sifter.py

示例3: stdin

# 需要導入模塊: import time [as 別名]
# 或者: from time import strftime [as 別名]
def stdin(message, params, upper=False, lower=False):
    """ask for option/input from user"""

    symbol = colored("[OPT]", "magenta")
    currentime = colored("[{}]".format(time.strftime("%H:%M:%S")), "green")

    option = raw_input("{} {} {}: ".format(symbol, currentime, message))

    if upper:
        option = option.upper()
    elif lower:
        option = option.lower()

    while option not in params:
        option = raw_input("{} {} {}: ".format(symbol, currentime, message))

        if upper:
            option = option.upper()
        elif lower:
            option = option.lower()

    return option 
開發者ID:the-robot,項目名稱:sqliv,代碼行數:24,代碼來源:std.py

示例4: get_standings

# 需要導入模塊: import time [as 別名]
# 或者: from time import strftime [as 別名]
def get_standings(standings_option='all', date_str=None, args_filter=None):
    """Displays standings."""
    LOG.debug('Getting standings for %s, option=%s', date_str, standings_option)
    if date_str == time.strftime("%Y-%m-%d"):
        # strip out date string from url (issue #5)
        date_str = None
    if util.substring_match(standings_option, 'all') or util.substring_match(standings_option, 'division'):
        display_division_standings(date_str, args_filter, rank_tag='divisionRank', header_tags=('league', 'division'))
        if util.substring_match(standings_option, 'all'):
            print('')
    if util.substring_match(standings_option, 'all') or util.substring_match(standings_option, 'wildcard'):
        _display_standings('wildCard', 'Wildcard', date_str, args_filter, rank_tag='wildCardRank', header_tags=('league', ))
        if util.substring_match(standings_option, 'all'):
            print('')
    if util.substring_match(standings_option, 'all') or util.substring_match(standings_option, 'overall') \
            or util.substring_match(standings_option, 'league') or util.substring_match(standings_option, 'conference'):
        _display_standings('byLeague', 'League', date_str, args_filter, rank_tag='leagueRank', header_tags=('league', ))
        if util.substring_match(standings_option, 'all'):
            print('')

    if util.substring_match(standings_option, 'playoff') or util.substring_match(standings_option, 'postseason'):
        _display_standings('postseason', 'Playoffs', date_str, args_filter)
    if util.substring_match(standings_option, 'preseason'):
        _display_standings('preseason', 'Preseason', date_str, args_filter) 
開發者ID:kmac,項目名稱:mlbv,代碼行數:26,代碼來源:standings.py

示例5: save_playlist_to_file

# 需要導入模塊: import time [as 別名]
# 或者: from time import strftime [as 別名]
def save_playlist_to_file(self, stream_url):
        headers = {
            "Accept": "*/*",
            "Accept-Encoding": "identity",
            "Accept-Language": "en-US,en;q=0.8",
            "Connection": "keep-alive",
            "User-Agent": self.user_agent,
            "Cookie": self.access_token
        }
        # util.log_http(stream_url, 'get', headers, sys._getframe().f_code.co_name)
        resp = self.session.get(stream_url, headers=headers)
        playlist = resp.text
        playlist_file = os.path.join(util.get_tempdir(), 'playlist-{}.m3u8'.format(time.strftime("%Y-%m-%d")))
        LOG.info('Writing playlist to: %s', playlist_file)
        with open(playlist_file, 'w') as outf:
            outf.write(playlist)
        LOG.debug('save_playlist_to_file: %s', playlist) 
開發者ID:kmac,項目名稱:mlbv,代碼行數:19,代碼來源:session.py

示例6: take_adv_picture

# 需要導入模塊: import time [as 別名]
# 或者: from time import strftime [as 別名]
def take_adv_picture(self, num_of_pic, seconds_between):
		logging.debug("Webcam: Trying to take pictures")
		try:
			self.cam.start()
		except SystemError as se: # device path wrong
			logging.error("Webcam: Wasn't able to find video device at device path: %s" % self.path)
			return
		except AttributeError as ae: # init failed, taking pictures won't work -> shouldn't happen but anyway
			logging.error("Webcam: Couldn't take pictures because video device wasn't initialized properly")
			return

		try:
			for i in range(0,num_of_pic):
				img = self.cam.get_image()
				pygame.image.save(img, "%s/%s_%d.jpg" % (self.data_path, time.strftime("%Y%m%d_%H%M%S"), i))
				time.sleep(seconds_between)
		except Exception as e:
			logging.error("Webcam: Wasn't able to take pictures: %s" % e)

		self.cam.stop()
		logging.debug("Webcam: Finished taking pictures") 
開發者ID:SecPi,項目名稱:SecPi,代碼行數:23,代碼來源:webcam.py

示例7: initUI

# 需要導入模塊: import time [as 別名]
# 或者: from time import strftime [as 別名]
def initUI(self):
 
        self.box = QtGui.QComboBox(self)

        for i in self.formats:
            self.box.addItem(strftime(i))

        insert = QtGui.QPushButton("Insert",self)
        insert.clicked.connect(self.insert)
 
        cancel = QtGui.QPushButton("Cancel",self)
        cancel.clicked.connect(self.close)
 
        layout = QtGui.QGridLayout()

        layout.addWidget(self.box,0,0,1,2)
        layout.addWidget(insert,1,0)
        layout.addWidget(cancel,1,1)
        
        self.setGeometry(300,300,400,80)
        self.setWindowTitle("Date and Time")
        self.setLayout(layout) 
開發者ID:goldsborough,項目名稱:Writer,代碼行數:24,代碼來源:datetime.py

示例8: sshStopCron

# 需要導入模塊: import time [as 別名]
# 或者: from time import strftime [as 別名]
def sshStopCron(retry,hostname):
    global user
    global password
    if retry == 0:
        print "Stop Cron Failed in", hostname
        q.task_done()
        return
    try:
        s = paramiko.SSHClient()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if os.path.isfile(password) == True:
            s.connect(hostname, username=user, key_filename = password, timeout=60)
        else:
            s.connect(hostname, username=user, password = password, timeout=60)
        transport = s.get_transport()
        session = transport.open_session()
        session.set_combine_stderr(True)
        session.get_pty()
        command = "sudo mv /etc/cron.d/ifagent InsightAgent-master/ifagent."+time.strftime("%Y%m%d%H%M%S")+"\n"
        session.exec_command(command)
        stdin = session.makefile('wb', -1)
        stdout = session.makefile('rb', -1)
        stdin.write(password+'\n')
        stdin.flush()
        session.recv_exit_status() #wait for exec_command to finish
        s.close()
        print "Stopped Cron in ", hostname
        q.task_done()
        return
    except paramiko.SSHException, e:
        print "Invalid Username/Password for %s:"%hostname , e
        return sshStopCron(retry-1,hostname) 
開發者ID:insightfinder,項目名稱:InsightAgent,代碼行數:34,代碼來源:stopcron.py

示例9: getFileNameList

# 需要導入模塊: import time [as 別名]
# 或者: from time import strftime [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

示例10: checkNewVMs

# 需要導入模塊: import time [as 別名]
# 或者: from time import strftime [as 別名]
def checkNewVMs(vmDomains):
    newVMNames = []
    vmMetaDataFilePath = os.path.join(homePath, dataDirectory + "totalVMs.json")
    for vmDomain in vmDomains:
        newVMNames.append(vmDomain.name())
    if os.path.isfile(vmMetaDataFilePath) == False:
        towritePreviousVM = {}
        towritePreviousVM["allVM"] = newVMNames
        with open(vmMetaDataFilePath, 'w') as vmMetaDataFile:
            json.dump(towritePreviousVM, vmMetaDataFile)
    else:
        with open(vmMetaDataFilePath, 'r') as vmMetaDataFile:
            oldVMDomains = json.load(vmMetaDataFile)["allVM"]
        if cmp(newVMNames, oldVMDomains) != 0:
            towritePreviousVM = {}
            towritePreviousVM["allVM"] = newVMNames
            with open(vmMetaDataFilePath, 'w') as vmMetaDataFile:
                json.dump(towritePreviousVM, vmMetaDataFile)
            if os.path.isfile(os.path.join(homePath, dataDirectory + date + ".csv")) == True:
                oldFile = os.path.join(homePath, dataDirectory + date + ".csv")
                newFile = os.path.join(homePath, dataDirectory + date + "." + time.strftime("%Y%m%d%H%M%S") + ".csv")
                os.rename(oldFile, newFile) 
開發者ID:insightfinder,項目名稱:InsightAgent,代碼行數:24,代碼來源:getmetrics_kvm.py

示例11: checkNewInstances

# 需要導入模塊: import time [as 別名]
# 或者: from time import strftime [as 別名]
def checkNewInstances(instances):
    newInstances = []
    currentDate = time.strftime("%Y%m%d")
    instancesMetaDataFilePath = os.path.join(homePath, dataDirectory + "totalVMs.json")
    for instance in instances:
        newInstances.append(instance[1])
    if os.path.isfile(instancesMetaDataFilePath) == False:
        towritePreviousInstances = {}
        towritePreviousInstances["allInstances"] = newInstances
        with open(instancesMetaDataFilePath, 'w') as instancesMetaDataFile:
            json.dump(towritePreviousInstances, instancesMetaDataFile)
    else:
        with open(instancesMetaDataFilePath, 'r') as instancesMetaDataFile:
            oldInstances = json.load(instancesMetaDataFile)["allInstances"]
        if cmp(newInstances, oldInstances) != 0:
            towritePreviousInstances = {}
            towritePreviousInstances["allInstances"] = newInstances
            with open(instancesMetaDataFilePath, 'w') as instancesMetaDataFile:
                json.dump(towritePreviousInstances, instancesMetaDataFile)
            if os.path.isfile(os.path.join(homePath, dataDirectory + currentDate + ".csv")) == True:
                oldFile = os.path.join(homePath, dataDirectory + currentDate + ".csv")
                newFile = os.path.join(homePath,
                                       dataDirectory + currentDate + "." + time.strftime("%Y%m%d%H%M%S") + ".csv")
                os.rename(oldFile, newFile) 
開發者ID:insightfinder,項目名稱:InsightAgent,代碼行數:26,代碼來源:getmetrics_jolokia.py

示例12: __init__

# 需要導入模塊: import time [as 別名]
# 或者: from time import strftime [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

示例13: createBuiltinDefines

# 需要導入模塊: import time [as 別名]
# 或者: from time import strftime [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

示例14: __init__

# 需要導入模塊: import time [as 別名]
# 或者: from time import strftime [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

示例15: getbmsdat

# 需要導入模塊: import time [as 別名]
# 或者: from time import strftime [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


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