• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python time.localtime函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中time.localtime函数的典型用法代码示例。如果您正苦于以下问题:Python localtime函数的具体用法?Python localtime怎么用?Python localtime使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了localtime函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: format_date

def format_date(timestamp):
    FORY = '%Y-%m-%d @ %H:%M'
    FORM = '%m-%d @ %H:%M'
    FORH = '%H:%M'
    os.environ["TZ"] = config.default_timezone
    time.tzset()
    r_time = time.strftime(FORM, time.localtime(timestamp))
    h_time = time.strftime(FORH, time.localtime(timestamp))
    now = int(time.time())
    t = now - timestamp
    if t < 60:
        format_str = '刚刚'
    elif t < 60 * 60:
        min = t / 60
        format_str = '%d 分钟前' % min
    elif t < 60 * 60 * 24:
        h = t / (60 * 60)
        format_str = '%d 小时前 %s' % (h, h_time)
    elif t < 60 * 60 * 24 * 3:
        d = t / (60 * 60 * 24)
        if d == 1:
            format_str = '昨天 ' + r_time
        else:
            format_str = '前天 ' + r_time
    else:
        format_str = time.strftime(FORY, time.localtime(timestamp))
    return format_str
开发者ID:wbbim,项目名称:collipa,代码行数:27,代码来源:helpers.py


示例2: delete

    def delete(self, thema, id, beitragID=None):
        discussionpath = "./data/themen/" + thema + "/" + id + ".json"
        with open(discussionpath, "r") as discussionfile:
            discussion = json.load(discussionfile)

        if beitragID == None:
            if discussion["Status"] == "deleted":
                discussion["Status"] = " "
            else:
                discussion["Status"] = "deleted"

            discussion["Bearbeiter"] = cherrypy.session["Benutzername"]
            discussion["Bearbeitet"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        else:
            for post in discussion["Beitraege"]:
                if post["ID"] == beitragID:
                    if post["Status"] == "deleted":
                        post["Status"] = " "
                    else:
                        post["Status"] = "deleted"
                    post["Bearbeiter"] = cherrypy.session["Benutzername"]
                    post["Bearbeitet"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        with open(discussionpath, "w") as discussionfile:
            json.dump(discussion, discussionfile, indent=4)
开发者ID:fr34kyn01535,项目名称:PyForum,代码行数:25,代码来源:datenbank.py


示例3: countQuery

def countQuery(dbSpace):
    dbSpace.queryCount += 1
    if time.localtime()[4] > dbSpace.queryMinCur:
        dbSpace.queryMinCur = time.localtime()[4]
        dbSpace.lastQueryPerMin = dbSpace.queryMinCount
    else:
        dbSpace.queryMinCount += 1
开发者ID:jairhenrique,项目名称:iskdaemon,代码行数:7,代码来源:ImageDB.py


示例4: cmd_list

  def cmd_list(self, args):
    """
    @G%(name)[email protected] - @B%(cmdname)[email protected]
      list timers and the plugins they are defined in
      @[email protected]: list
    """
    tmsg = []

    match = args['match']

    tmsg.append('Local time is: %s' % time.strftime('%a %b %d %Y %H:%M:%S',
                                                    time.localtime()))

    tmsg.append('%-20s : %-13s %-9s %-8s %s' % ('Name', 'Defined in',
                                                'Enabled', 'Fired', 'Next Fire'))
    for i in self.timerlookup:
      if not match or match in i:
        timerc = self.timerlookup[i]
        tmsg.append('%-20s : %-13s %-9s %-8s %s' % (
            timerc.name, timerc.plugin.sname,
            timerc.enabled, timerc.timesfired,
            time.strftime('%a %b %d %Y %H:%M:%S',
                          time.localtime(timerc.nextcall))))

    return True, tmsg
开发者ID:endavis,项目名称:bastproxy,代码行数:25,代码来源:timers.py


示例5: generateur

def generateur(presence) : # a si le ficher et present, w sinon
	global cible
	global nom
	global type
	pasdefichier = open(cible + ".txt", presence) # Ouvre le fichier
	fdebug("Ouvert / cree le fichier")
	continueraecrire = "c"
	while continueraecrire is not "q" :
		if type is "a" :
			action = raw_input ( VERT + "Entre l'action a inscrire dans le registre >>>" + NORMAL )
			while action == "" :
				print (ROUGE + "Entre quelque chose" + NORMAL )
				action = raw_input ( VERT + "Entre l'action a inscrire dans le registre >>>" + NORMAL )
			pasdefichier.write(time.strftime('%d/%m/%y %H:%M',time.localtime()) + " *** " + action + "(" + nom + ")"+ "\n")
		else : 
			commantaire = raw_input( VERT + "Entre le commentaire a inscrire dans le casier >>>" + NORMAL )
			while commantaire == "" :
				print (ROUGE + "Entre quelque chose" + NORMAL )
				commantaire = raw_input( VERT + "Entre le commentaire a inscrire dans le casier >>>" + NORMAL )
			pasdefichier.write(time.strftime('%d/%m/%y %H:%M',time.localtime()) + " >>> " + commantaire + " (" + nom + ")"+ "\n")
		fdebug("Enregistrement dans le fichier")
		warn = raw_input(VERT + "Avez vous prevenu " + cible + " pour la faute ? (o/n) " + NORMAL)
		if "o" in warn :
			pasdefichier.write(time.strftime('%d/%m/%y %H:%M',time.localtime()) + " *** " + "warn " + "(" + nom + ")"+ "\n")
		continueraecrire = raw_input(VERT + "Continuer a écrire sur la meme personne ?(q pour quitter , c pour continuer)" + NORMAL)
	pasdefichier.close() # Je ferme la porte derriere mon fichier
开发者ID:paris-ci,项目名称:Casiers,代码行数:26,代码来源:python.py


示例6: add_separator

    def add_separator(self, timestamp):
        '''Add whitespace and timestamp between chat sessions.'''
        time_with_current_year = \
            (time.localtime(time.time())[0], ) + \
            time.strptime(timestamp, '%b %d %H:%M:%S')[1:]

        timestamp_seconds = time.mktime(time_with_current_year)
        if timestamp_seconds > time.time():
            time_with_previous_year = \
                (time.localtime(time.time())[0] - 1, ) + \
                time.strptime(timestamp, '%b %d %H:%M:%S')[1:]
            timestamp_seconds = time.mktime(time_with_previous_year)

        message = TextBox(self,
                          style.COLOR_BUTTON_GREY, style.COLOR_BUTTON_GREY,
                          style.COLOR_WHITE, style.COLOR_BUTTON_GREY, False,
                          None, timestamp_to_elapsed_string(timestamp_seconds))
        self._message_list.append(message)
        box = Gtk.HBox()
        align = Gtk.Alignment.new(
            xalign=0.5, yalign=0.0, xscale=0.0, yscale=0.0)
        box.pack_start(align, True, True, 0)
        align.show()
        align.add(message)
        message.show()
        self._conversation.attach(box, 0, self._row_counter, 1, 1)
        box.show()
        self._row_counter += 1
        self.add_log_timestamp(timestamp)
        self._last_msg_sender = None
开发者ID:leonardcj,项目名称:speak,代码行数:30,代码来源:chatbox.py


示例7: _fix_review_dates

    def _fix_review_dates(self, item):
        ''' Convert dates so ES detect them '''


        for date_field in ['timestamp','createdOn','lastUpdated']:
            if date_field in item.keys():
                date_ts = item[date_field]
                item[date_field] = time.strftime('%Y-%m-%dT%H:%M:%S',
                                                  time.localtime(date_ts))
        if 'patchSets' in item.keys():
            for patch in item['patchSets']:
                pdate_ts = patch['createdOn']
                patch['createdOn'] = time.strftime('%Y-%m-%dT%H:%M:%S',
                                                   time.localtime(pdate_ts))
                if 'approvals' in patch:
                    for approval in patch['approvals']:
                        adate_ts = approval['grantedOn']
                        approval['grantedOn'] = \
                            time.strftime('%Y-%m-%dT%H:%M:%S',
                                          time.localtime(adate_ts))
        if 'comments' in item.keys():
            for comment in item['comments']:
                cdate_ts = comment['timestamp']
                comment['timestamp'] = time.strftime('%Y-%m-%dT%H:%M:%S',
                                                     time.localtime(cdate_ts))
开发者ID:pombredanne,项目名称:GrimoireELK,代码行数:25,代码来源:gerrit.py


示例8: mylocaltime

def mylocaltime(sec=None, mode=None):
    from scal3.cal_types import convert
    if mode==None:##DATE_GREG
        return list(localtime(sec))
    t = list(localtime(sec))
    t[:3] = convert(t[0], t[1], t[2], DATE_GREG, mode)
    return t
开发者ID:hedayat,项目名称:starcal,代码行数:7,代码来源:core.py


示例9: recomByBasewalker

def recomByBasewalker(graph, targetNode, newCoAuthorList, recom_count, \
        file_input, file_input_re, max_iterations, damping_factor):
    recom_list = []
    file_input.write('befor BaseWalker time:' + time.strftime('%Y-%m-%d-%H-%M-%S', \
            time.localtime(time.time())) + '\n')
    pagerank = PageRank(0, graph, targetNode, damping_factor, max_iterations)
    file_input.write('after BaseWalker time:' + time.strftime('%Y-%m-%d-%H-%M-%S', \
            time.localtime(time.time())) + '\n')
    index = 0
    for k, v in pagerank:
#        if not graph.has_edge((targetNode, k)):
        recom_list.append(k)
        file_input.write('recom:' + '(' + targetNode + ':' + k + ')' + str(v) + '\n')
        index += 1
        if index >= recom_count - 1:
            break
    pagerank = []
    file_input.write(str(newCoAuthorList) + '\n')
    node_count_right = len(list(set(newCoAuthorList) & set(recom_list)))
    path_dis = find_shortest_path(graph, targetNode, recom_list)
    file_input_re.write('2'+str(len(newCoAuthorList)) + ' ' + str(node_count_right) + \
            ' ' + str(recom_count) + ' ' + str((1.0*path_dis)/recom_count) + '\n')
    recom_list = []
    '''return the percision,recall and average of shortest path leghth'''
    return (1.0*node_count_right)/recom_count, (1.0*node_count_right)/len(newCoAuthorList), (1.0*path_dis)/recom_count
开发者ID:helloworld163,项目名称:MVCWalker,代码行数:25,代码来源:main.py


示例10: print_

 def print_(self, dic, cnt):
     if self.subtype == 'bot_message':
         print(str(cnt) + ' BOT名前: {0} : {1} ID:{2}\n'.format(
               dic[self.user],
               time.strftime("%Y/%m/%d %a %H:%M:%S",
                             time.localtime(float(self.ts))), self.user))
         print('\t' + self.getTextAs2CH(dic) + '\n')
     elif self.subtype == 'me_message':
         print(str(cnt) + ' 名前: {0} : {1} ID:{2}\n'.format(dic[self.user],
               time.strftime("%Y/%m/%d %a %H:%M:%S",
               time.localtime(float(self.ts))), self.user) +
               'Type: /me message')
         print('\t' + self.getTextAs2CH(dic) + '\n')
     elif self.subtype == 'message_changed':
         print(str(cnt) + ' 名前: {0} : {1} ID:{2}\n'.format(dic[self.user],
               time.strftime("%Y/%m/%d %a %H:%M:%S",
               time.localtime(float(self.ts))), self.user) +
               'Type: /me message')
         print('\t' + self.getTextAs2CH(dic) + '\n')
         print('Edited by {0} at {1}\n'.format(
               dic[self.edit_user],
               time.strftime("%Y/%m/%d %a %H:%M:%S",
                             time.localtime(float(self.edit_ts)))))
     else:
         print(str(cnt) + ' 名前: {0} : {1} ID:{2}\n'.format(dic[self.user],
               time.strftime("%Y/%m/%d %a %H:%M:%S",
               time.localtime(float(self.ts))), self.user))
         print('\t' + self.getTextAs2CH(dic) + '\n')
开发者ID:terry182,项目名称:2chSlackChatHistory,代码行数:28,代码来源:msg.py


示例11: png

 def png(self, start_timestamp, end_timestamp):
     self.load(start_timestamp, end_timestamp)
     plt.figure(figsize=(10, 7.52))
     plt.rc("axes", labelsize=12, titlesize=14)
     plt.rc("font", size=10)
     plt.rc("legend", fontsize=7)
     plt.rc("xtick", labelsize=8)
     plt.rc("ytick", labelsize=8)
     plt.axes([0.08, 0.08, 1 - 0.27, 1 - 0.15])
     for plot in self.plots:
         plt.plot(self.timestamps, self.plots[plot], self.series_fmt(plot), label=self.series_label(plot))
     plt.axis("tight")
     plt.gca().xaxis.set_major_formatter(
         matplotlib.ticker.FuncFormatter(lambda x, pos=None: time.strftime("%H:%M\n%b %d", time.localtime(x)))
     )
     plt.gca().yaxis.set_major_formatter(
         matplotlib.ticker.FuncFormatter(lambda x, pos=None: locale.format("%.*f", (0, x), True))
     )
     plt.grid(True)
     plt.legend(loc=(1.003, 0))
     plt.xlabel("Time/Date")
     plt.title(
         self.description()
         + "\n%s to %s"
         % (
             time.strftime("%H:%M %d-%b-%Y", time.localtime(start_timestamp)),
             time.strftime("%H:%M %d-%b-%Y", time.localtime(end_timestamp)),
         )
     )
     output_buffer = StringIO.StringIO()
     plt.savefig(output_buffer, format="png")
     return output_buffer.getvalue()
开发者ID:rbroemeling,项目名称:udplogger,代码行数:32,代码来源:Graphs.py


示例12: getSearchSimilarEpg

def getSearchSimilarEpg(ref, eventid):
	ref = unquote(ref)
	ret = []
	ev = {}
	epgcache = eEPGCache.getInstance()
	events = epgcache.search(('IBDTSENR', 128, eEPGCache.SIMILAR_BROADCASTINGS_SEARCH, ref, eventid));
	if events is not None:
		for event in events:
			ev = {}
			ev['id'] = event[0]
			ev['date'] = "%s %s" % (tstrings[("day_" + strftime("%w", (localtime(event[1]))))], strftime("%d.%m.%Y", (localtime(event[1]))))
			ev['begin_timestamp'] = event[1]
			ev['begin'] = strftime("%H:%M", (localtime(event[1])))
			ev['duration_sec'] = event[2]
			ev['duration'] = int(event[2] / 60)
			ev['end'] = strftime("%H:%M",(localtime(event[1] + event[2])))
			ev['title'] = event[3]
			ev['shortdesc'] = convertDesc(event[4])
			ev['longdesc'] = convertDesc(event[5])
			ev['sref'] = event[7]
			ev['sname'] = filterName(event[6])
			ev['picon'] = getPicon(event[7])
			ev['now_timestamp'] = None
			ret.append(ev)

	return { "events": ret, "result": True }
开发者ID:Dima73,项目名称:e2openplugin-OpenWebif,代码行数:26,代码来源:services.py


示例13: date_format

def date_format(epoch):
    """given an epoch, return a unix-ls like formatted string"""

    time_tuple = time.localtime(epoch)
    if time.localtime().tm_year != time_tuple.tm_year:
        return time.strftime('%b %d  %Y ', time_tuple)
    return time.strftime('%b %d %H:%M ', time_tuple)
开发者ID:canfar,项目名称:vos,代码行数:7,代码来源:vls.py


示例14: newFunc

 def newFunc(*args, **args2):
     t0 = time.time()
     print "@%s, {%s} start" % (time.strftime("%X", time.localtime()), func.__name__)
     back = func(*args, **args2)
     print "@%s, {%s} end" % (time.strftime("%X", time.localtime()), func.__name__)
     print "@%.3fs taken for {%s}" % (time.time() - t0, func.__name__)
     return back
开发者ID:mingxuan,项目名称:RnnSearch,代码行数:7,代码来源:utils.py


示例15: setup

    def setup(self):
        self.record = ACROSCORE + strftime('%Y-%m-%d-%H%M') + '.game'
        open(self.record, "w")

        self.active = True

        self.cumulative = {}
        self.start = mktime(localtime())
        self.mark = mktime(localtime())
        self.round = 1

        self.stage = "waiting"

        self.matchlast = False
        self.killgame = False
        self.warned = False
        self.bypass = False
        self.displayed = False

        self.voters = []
        self.players = []
        self.gimps = {}
        self.selfsubbed = False
        self.paused = False
        self.killgame = False
开发者ID:joshuabergeron,项目名称:MongoBot,代码行数:25,代码来源:acro.py


示例16: recommender

def recommender( recom_count = 25, test_times = 100, hotNode_degree = 60, year_sta = 2011):
    '''
    进行推荐实验,计算结果存储在txt文件中
    @edge_del       随机删掉的边数
    @recom_count    推荐列表大小
    @test_times     实验次数
    @hotNode_degree 定义热点最小邻居数
    '''
    file_input = open('/home/zhenchentl/out.txt','w+')
    file_input_re = open('/home/zhenchentl/out_re.txt','w+')
    file_input.write('recom_count:' + str(recom_count) + '\n')
    file_input.write('test_times:' + str(test_times) + '\n')
    file_input.write('hotNode_degree:' + str(hotNode_degree) + '\n')

    file_input.write('befor get graph time:' + time.strftime('%Y-%m-%d-%H-%M-%S', \
            time.localtime(time.time())) + '\n')
    print 'befor get graph time:' + time.strftime('%Y-%m-%d-%H-%M-%S', \
            time.localtime(time.time()))
    '''get the graph based on the coauhtor relationship'''
    mD = DigraphByYear()
    mDigraph = mD.getDigraph()
    getGraphAttr(mDigraph, file_input)
    file_input.write('after get graph time:' + time.strftime('%Y-%m-%d-%H-%M-%S', \
            time.localtime(time.time())) + '\n')
    print 'after get graph time:' + time.strftime('%Y-%m-%d-%H-%M-%S', \
            time.localtime(time.time()))
    recom_count = 5
    while(recom_count <= 100):
        exp_recom(mDigraph, file_input,file_input_re,recom_count)
        recom_count += 5
    file_input.close()
    file_input_re.close()
开发者ID:helloworld163,项目名称:MVCWalker,代码行数:32,代码来源:main.py


示例17: newCalib

    def newCalib(self,calibName=None,
        width=None,
        distance=None,
        gamma=None,
        notes=None,
        useBits=False,
        verbose=True):
        """create a new (empty) calibration for this monitor and
        makes this the current calibration"""
        if calibName==None:
            calibName= strFromDate(time.localtime())
        #add to the list of calibrations
        self.calibNames.append(calibName)
        self.calibs[calibName]={}

        self.setCurrent(calibName)
        #populate with some default values:
        self.setCalibDate(time.localtime())
        self.setGamma(gamma)
        self.setWidth(width)
        self.setDistance(distance)
        self.setNotes(notes)
        self.setPsychopyVersion(__version__)
        self.setUseBits(useBits)
        newGrid=numpy.ones((4,3), 'd')
        newGrid[:,0] *= 0
        self.setGammaGrid(newGrid)
        self.setLineariseMethod(1)
开发者ID:9173860,项目名称:psychopy,代码行数:28,代码来源:calibTools.py


示例18: exec_cmd

	def exec_cmd(self):
		global texto1
		print "Soy el hilo"
		self.miSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.miSocket.bind(("192.168.1.2", 4545))
		self.miSocket.settimeout(1)
		self.miSocket.listen(2)
		print("Esperando conexion")
		while hilo:
			try:
				self.channel, details = self.miSocket.accept()
			except:
				pass
			else:
				self.channel.settimeout(1)
				self.channel.send("OK\n")
				print "OK enviado"
				print "Esperando recibir, hilo = ",hilo
				while hilo:
					try:
						texto1 = self.channel.recv(1024)
					except:
						pass
					else:
						self.entry_lat.set_text("Leyendo")
						self.entry_long.set_text("posicion")
						self.new_thread(self.guardar)
						self.buffer.insert_at_cursor("Recibido :"+texto1+"\n")
						print time.localtime(time.time())
						print "recibido", texto1
						if texto1 == "quit":
							break
		print "Cerrando el socket"
		self.miSocket.shutdown(self.miSocket)
		self.miSocket.close()
开发者ID:drmelectronic,项目名称:econadmin1v0,代码行数:35,代码来源:servidor.py


示例19: on_data

 def on_data(self, data):
     if time.time() >= self.started + self.duration:
         stats = open('{0}-sample.stats'.format(int(self.started)), 'w+')
         stats.write("================= STATISTICS =================" + "\n")
         stats.write("Start time: " + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.started)) + "\n")
         stats.write("End time: " + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) + "\n")
         stats.write("First Tweet ID: " + self.first_tweet_id + "\n")
         stats.write("Last Tweet ID: " + self.last_tweet_id + "\n")
         stats.write("Language: " + self.lang + "\n")
         stats.write("Language classification threshold: " + str(self.lang_threshold) + "\n")
         stats.write("Above threshold: " + str(self.counter[self.lang + '-above']) + "\n")
         stats.write("Below threshold: " + str(self.counter[self.lang + '-below']) + "\n")
         stats.write("Exluded: " + str(self.counter['excluded']) + "\n")
         return False
     elif 'in_reply_to_status_id' in data: 
         status = Status.parse(self.api, json.loads(data))
         langclass = langid.classify(status.text)
         
         if (self.counter == {self.lang + '-above':0, self.lang + '-below':0, 'excluded':0}):
             self.first_tweet_id = str(status.id)
         self.last_tweet_id = str(status.id)
         
         if (langclass[0] == self.lang):                
             if langclass[1] >= self.lang_threshold:
                 self.above_output.write(data)
                 self.counter[self.lang + '-above'] += 1
             else:
                 self.below_output.write(data)
                 self.counter[self.lang + '-below'] += 1
         else:
             self.excl_output.write(data)
             self.counter['excluded'] += 1
            
         return True
开发者ID:StijnPieper,项目名称:wse,代码行数:34,代码来源:SampleDownloader.py


示例20: lastlogExit

 def lastlogExit(self):
     starttime = time.strftime("%a %b %d %H:%M", time.localtime(self.logintime))
     endtime = time.strftime("%H:%M", time.localtime(time.time()))
     duration = utils.durationHuman(time.time() - self.logintime)
     f = file("%s/lastlog.txt" % self.env.cfg.get("honeypot", "data_path"), "a")
     f.write("root\tpts/0\t%s\t%s - %s (%s)\n" % (self.clientIP, starttime, endtime, duration))
     f.close()
开发者ID:RyanKung,项目名称:cowrie,代码行数:7,代码来源:protocol.py



注:本文中的time.localtime函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python time.mktime函数代码示例发布时间:2022-05-27
下一篇:
Python time.gmtime函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap