本文整理汇总了Python中time.localtime函数的典型用法代码示例。如果您正苦于以下问题:Python localtime函数的具体用法?Python localtime怎么用?Python localtime使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了localtime函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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)
示例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
示例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
示例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
示例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
示例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))
示例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
示例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
示例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')
示例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()
示例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 }
示例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)
示例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
示例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