本文整理汇总了Python中time.strftime函数的典型用法代码示例。如果您正苦于以下问题:Python strftime函数的具体用法?Python strftime怎么用?Python strftime使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了strftime函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_statement
def create_statement(self, cr, uid, line_invoice, partner, amount, journal, date_bank=None, account_id=None):
bank_stmt_id = self.acc_bank_stmt_model.create(
cr, uid, {"journal_id": journal, "date": date_bank or time.strftime("%Y") + "-07-01"}
)
bank_stmt_line_id = self.acc_bank_stmt_line_model.create(
cr,
uid,
{
"name": "payment",
"statement_id": bank_stmt_id,
"partner_id": partner,
"amount": amount,
"date": date_bank or time.strftime("%Y") + "-07-01",
},
)
val = {
"credit": amount > 0 and amount or 0,
"debit": amount < 0 and amount * -1 or 0,
"name": line_invoice and line_invoice.name or "cash flow",
}
if line_invoice:
val.update({"counterpart_move_line_id": line_invoice.id})
if account_id:
val.update({"account_id": account_id})
self.acc_bank_stmt_line_model.process_reconciliation(cr, uid, bank_stmt_line_id, [val])
move_line_ids_complete = self.acc_bank_stmt_model.browse(cr, uid, bank_stmt_id).move_line_ids
return move_line_ids_complete
示例2: 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()
示例3: saveVerbrauchsData
def saveVerbrauchsData(v_wp,v_sz,zs_wp,zs_sz,interval):
y = time.strftime('%Y', time.localtime())
m = time.strftime('%m', time.localtime())
d = time.strftime('%d', time.localtime())
f = open("/var/lib/heatpumpMonitor/verbrauch.%s-%s-%s" %(y,m,d) , 'a')
f.write("%s %04d %04d %d %d %d\n" % (time.strftime('%Y %m %d %a %H %H:%M:%S', time.localtime()), v_wp, v_sz, zs_wp, zs_sz, interval))
f.close
示例4: 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)
示例5: run_once
def run_once(self, test_name):
if test_name == 'setup':
return
#
# We need to be sure we run this on the right target machines
# as this is really quite destructive!
#
if not os.uname()[1] in self.valid_clients:
return
date_start = time.strftime("%Y-%m-%d")
time_start = time.strftime("%H%M")
output = ''
#
# Test 3 different I/O schedulers:
#
for iosched in ['cfq', 'deadline', 'noop']:
#
# Test 5 different file systems, across 20+ tests..
#
os.chdir(self.fio_tests_dir)
cmd = './test.sh'
cmd += ' -d ' + self.dev + '1 -m 8G -S -s ' + iosched + ' -f ext2,ext3,ext4,xfs,btrfs'
cmd += ' -D ' + date_start + ' -T ' + time_start
output += utils.system_output(cmd, retain_output=True)
#
# Move the results from the src tree into the autotest results tree where it will automatically
# get picked up and copied over to the jenkins server.
#
os.rename(os.path.join(self.srcdir, 'fs-test-proto'), os.path.join(self.resultsdir, 'fs-test-proto'))
示例6: createTestWorkspace
def createTestWorkspace(self):
""" Create a workspace for testing against with ideal log values
"""
from mantid.simpleapi import CreateWorkspace
from mantid.simpleapi import AddSampleLog
from time import gmtime, strftime,mktime
import numpy as np
# Create a matrix workspace
x = np.array([1.,2.,3.,4.])
y = np.array([1.,2.,3.])
e = np.sqrt(np.array([1.,2.,3.]))
wksp = CreateWorkspace(DataX=x, DataY=y,DataE=e,NSpec=1,UnitX='TOF')
# Add run_start
tmptime = strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(gmtime())))
AddSampleLog(Workspace=wksp,LogName='run_start',LogText=str(tmptime))
tsp_a=kernel.FloatTimeSeriesProperty("SensorA")
tsp_b=kernel.FloatTimeSeriesProperty("SensorB")
tsp_c=kernel.FloatTimeSeriesProperty("SensorC")
for i in arange(25):
tmptime = strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(gmtime())+i))
tsp_a.addValue(tmptime, 1.0*i*i)
tsp_b.addValue(tmptime, 2.0*i*i)
tsp_c.addValue(tmptime, 3.0*i*i)
wksp.mutableRun()['SensorA']=tsp_a
wksp.mutableRun()['SensorB']=tsp_b
wksp.mutableRun()['SensorC']=tsp_c
return wksp
示例7: 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
示例8: handle
def handle(self, data, fulltext, tokens, slackclient, channel, user):
slackclient.post_message(channel, 'UTC: `' + time.strftime('%Y/%m/%d-%H:%M:%S', time.gmtime(self._epoch)) + '`')
if self._additional_location and 'modules.google_tz_handler' in sys.modules:
handler_module = sys.modules['modules.google_tz_handler']
handler_class = getattr(handler_module, 'google_tz_handler')
handler_instance = handler_class(self._config)
slackclient.post_message(channel, self._additional_location + ': `' + time.strftime('%Y/%m/%d-%H:%M:%S', time.gmtime(handler_instance.get_raw_local_time(handler_instance.get_cities(self._additional_location.replace(' ', '+'))[0], self._epoch))) + '`')
示例9: do_export
def do_export(_):
left_idx = g_pool.seek_control.trim_left
right_idx = g_pool.seek_control.trim_right
export_range = left_idx, right_idx + 1 # exclusive range.stop
export_ts_window = pm.exact_window(g_pool.timestamps, (left_idx, right_idx))
export_dir = os.path.join(g_pool.rec_dir, "exports")
export_dir = next_export_sub_dir(export_dir)
os.makedirs(export_dir)
logger.info('Created export dir at "{}"'.format(export_dir))
export_info = {
"Player Software Version": str(g_pool.version),
"Data Format Version": meta_info["Data Format Version"],
"Export Date": strftime("%d.%m.%Y", localtime()),
"Export Time": strftime("%H:%M:%S", localtime()),
"Frame Index Range:": g_pool.seek_control.get_frame_index_trim_range_string(),
"Relative Time Range": g_pool.seek_control.get_rel_time_trim_range_string(),
"Absolute Time Range": g_pool.seek_control.get_abs_time_trim_range_string(),
}
with open(os.path.join(export_dir, "export_info.csv"), "w") as csv:
write_key_value_file(csv, export_info)
notification = {
"subject": "should_export",
"range": export_range,
"ts_window": export_ts_window,
"export_dir": export_dir,
}
g_pool.ipc_pub.notify(notification)
示例10: exec_cmd_servers
def exec_cmd_servers(username):
print '\nInput the \033[32mHost IP(s)\033[0m,Separated by Commas, q/Q to Quit.\n'
while True:
hosts = raw_input('\033[1;32mip(s)>: \033[0m')
if hosts in ['q', 'Q']:
break
hosts = hosts.split(',')
hosts.append('')
hosts = list(set(hosts))
hosts.remove('')
ip_all, ip_all_dict = ip_all_select(username)
no_perm = set(hosts)-set(ip_all)
if no_perm:
print "You have NO PERMISSION on %s..." % list(no_perm)
continue
print '\nInput the \033[32mCommand\033[0m , The command will be Execute on servers, q/Q to quit.\n'
while True:
cmd = raw_input('\033[1;32mCmd(s): \033[0m')
if cmd in ['q', 'Q']:
break
exec_log_dir = os.path.join(log_dir, 'exec_cmds')
if not os.path.isdir(exec_log_dir):
os.mkdir(exec_log_dir)
os.chmod(exec_log_dir, 0777)
filename = "%s/%s.log" % (exec_log_dir, time.strftime('%Y%m%d'))
f = open(filename, 'a')
f.write("DateTime: %s User: %s Host: %s Cmds: %s\n" %
(time.strftime('%Y/%m/%d %H:%M:%S'), username, hosts, cmd))
for host in hosts:
remote_exec_cmd(host, username, cmd)
示例11: strftime
def strftime(dt, fmt):
if dt.year >= 1900:
return super(type(dt), dt).strftime(fmt)
illegal_formatting = _illegal_formatting.search(fmt)
if illegal_formatting:
msg = 'strftime of dates before 1900 does not handle {0}'
raise TypeError(msg.format(illegal_formatting.group(0)))
year = dt.year
# for every non-leap year century, advance by
# 6 years to get into the 28-year repeat cycle
delta = 2000 - year
off = 6 * (delta // 100 + delta // 400)
year += off
# move to around the year 2000
year += ((2000 - year) // 28) * 28
timetuple = dt.timetuple()
s1 = time.strftime(fmt, (year,) + timetuple[1:])
sites1 = _findall(s1, str(year))
s2 = time.strftime(fmt, (year + 28,) + timetuple[1:])
sites2 = _findall(s2, str(year + 28))
sites = []
for site in sites1:
if site in sites2:
sites.append(site)
s = s1
syear = "%04d" % (dt.year,)
for site in sites:
s = s[:site] + syear + s[site + 4:]
return s
示例12: banIP
def banIP(IP, dport, service, timer = BANTIMER):
"""Returns 1 if IP is already BANNED/UNBANNED
Returns 0 if BANNED/UNBANNED successfully
"""
print 'banIP:'
if (IP, service) in bannedIPs:
print 'IP:' + IP + 'is already BANNED'
logging.info('IP:' + IP + 'is already BANNED')
return 1
else:
ip = bannedIP(IP, time.time(), service, timer)
chain = iptc.Chain(iptc.Table(iptc.Table.FILTER), "INPUT")
ip.rule = iptc.Rule(chain=chain)
ip.rule.src = ip.IP + "/255.255.255.255"
ip.rule.protocol = "tcp"
ip.rule.target = iptc.Target(ip.rule, "REJECT")
ip.rule.target.reject_with = "icmp-admin-prohibited"
match = iptc.Match(ip.rule,"tcp")
match.dport = dport
ip.rule.add_match(match)
bannedIPs[(ip.IP, service)] = ip
chain.insert_rule(ip.rule)
print 'IP:' + ip.IP + ' BANNED at ' + time.strftime("%b %d %H:%M:%S")
logging.info('IP:' + ip.IP + ' BANNED at ' + time.strftime("%b %d %H:%M:%S"))
resp = {"action": BANNEDIP, "data":{"IP":ip.IP, "time":time.strftime("%b %d %H:%M:%S", time.localtime(ip.time)), "timer":ip.timer, "service":ip.service}}
server.send_message_to_all(json.dumps(resp))
示例13: set_filter_date
def set_filter_date(self):
dialog = xbmcgui.Dialog()
if self.start_date == '':
self.start_date = str(datetime.datetime.now())[:10]
if self.end_date == '':
self.end_date = str(datetime.datetime.now())[:10]
try:
d = dialog.numeric(1, common.getstring(30117) ,strftime("%d/%m/%Y",strptime(self.start_date,"%Y-%m-%d")) )
if d != '':
self.start_date = strftime("%Y-%m-%d",strptime(d.replace(" ","0"),"%d/%m/%Y"))
else:
self.start_date =''
common.log('', str(self.start_date))
d = dialog.numeric(1, common.getstring(30118) ,strftime("%d/%m/%Y",strptime(self.end_date,"%Y-%m-%d")) )
if d != '':
self.end_date = strftime("%Y-%m-%d",strptime(d.replace(" ","0"),"%d/%m/%Y"))
else:
self.end_date =''
common.log('', str(self.end_date))
except:
pass
if self.start_date != '' or self.end_date != '':
self.getControl( BUTTON_DATE ).setLabel( self.start_date + ' ... ' + self.end_date )
else:
self.getControl( BUTTON_DATE ).setLabel( common.getstring(30164) )
self.getControl( BUTTON_DATE ).setVisible(False)
self.getControl( BUTTON_DATE ).setVisible(True)
示例14: 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()
示例15: _format_data
def _format_data(self, start_time, timestamp, name, units, values):
fields = _fields[:]
file_timestamp = time.strftime('%Y%m%d%H%M',time.gmtime(start_time))
value_timestamp = time.strftime('%Y%m%d%H%M',time.gmtime(timestamp))
fields[_field_index['units']] = units
fields[_field_index['commodity']] = self.commodity
meter_id = name + '|1'
if units:
meter_id += '/%s' % units
fields[_field_index['meter_id']] = meter_id
fields[_field_index['receiver_id']] = ''
fields[_field_index['receiver_customer_id']] = self.customer_name + '|' + self.account_name
fields[_field_index['timestamp']] = file_timestamp
# interval put into "MMDDHHMM" with MMDD = 0000
fields[_field_index['interval']] = '0000%02d%02d' % (self.period / 3600, (self.period % 3600) / 60)
fields[_field_index['count']] = str(len(values))
value_sets = []
for value in values:
try:
value = '%f' % value
protocol_text = ''
except ValueError:
value = ''
protocol_text = 'N'
value_set = (value_timestamp, protocol_text, value)
value_sets.append(string.join(value_set, ','))
value_timestamp = ''
fields[_field_index['interval_data']] = string.join(value_sets, ',')
return string.join(fields, ',')