def flush_queue(self):
# check number of messages in queue
num_log_entries = self.log_queue.qsize()
if num_log_entries > 0:
# open the log file
with open(self.log_full_filename, 'ab') as log_file:
for i in range(num_log_entries):
log_entry = self.log_queue.get()
# append extra log information
current_time = log_entry['time']
current_time_str = time.asctime(time.localtime(current_time))
log_entry['localtime'] = current_time_str
# log the message as a JSON string
if isPython3:
log_file.write(bytes(json.dumps(log_entry) + "\n", 'UTF-8'))
else:
log_file.write(json.dumps(log_entry) + "\n")
python类localtime()的实例源码
def log(log_subsys, log_message, log_type='info', log_data=None):
current_time = time.time()
# form log entry dictionary
log_entry = {
'time' : current_time,
'subsys' : log_subsys,
'type' : log_type,
'message' : log_message,
}
if log_data is not None:
log_dict = dict(log_entry, **log_data)
else:
log_dict = log_entry
if Logger.debug:
print("LOG {:s} | {:s}".format(time.strftime("%H:%M:%S", time.localtime(current_time)), log_message))
# attempt to place in queue
try:
Logger.log_queue.put(log_dict)
except Queue.Full as e:
sys.stderr.write('Warning: log queue full, discarding message: "{:s}"\n'.format(log_message))
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("%Y-%m-%d %H:%M:%S", ct)
s = "%s,%03d" % (t, record.msecs)
return s
def disconnect(self):
flag = self.get_conn()
if len(flag) == 1:
handle = flag[0][0]
dialname = str(flag[0][1])
try:
win32ras.HangUp(handle)
self.saveData(False, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
logger.info("??" + dialname + "????")
return True
except Exception as e:
logger.info(dialname + "???????" + str(e.message))
# disconnect()
else:
logger.info("?????????????")
# ????????
def __built_table(self):
"""
??
:return:
"""
self.execute("""
CREATE TABLE test_results
(
case_id INTEGER PRIMARY KEY,
case_name TEXT,
device_name TEXT,
cpu_list TEXT,
mem_list TEXT,
execution_status TEXT,
created_time DATETIME DEFAULT (datetime('now', 'localtime'))
);""")
def mkdir_file(self):
"""
:return:?????????
"""
ini = U.ConfigIni()
result_file = str(ini.get_ini('test_case', 'log_file'))
result_file_every = result_file + '/' + \
time.strftime("%Y-%m-%d_%H_%M_%S{}".format(random.randint(10, 99)),
time.localtime(time.time()))
file_list = [
result_file,
result_file_every,
result_file_every + '/log',
result_file_every + '/per',
result_file_every + '/img',
result_file_every + '/status']
if not os.path.exists(result_file):
os.mkdir(result_file)
for file_path in file_list:
if not os.path.exists(file_path):
os.mkdir(file_path)
return result_file_every
def log(scan_type,host,port,info=''):
mutex.acquire()
time_str = time.strftime('%X', time.localtime( time.time()))
if scan_type == 'portscan':
print "[%s] %s:%d open"%(time_str,host,int(port))
elif scan_type == 'discern':
print "[%s] %s:%d is %s"%(time_str,host,int(port),info)
elif scan_type == 'active':
print "[%s] %s active" % (time_str, host)
elif info:
log = "[*%s] %s:%d %s %s"%(time_str,host,int(port),scan_type,info)
print log
log_file = open('result.log','a')
log_file.write(log+"\r\n")
log_file.close()
mutex.release()
def asctime(t=None):
"""
Convert a tuple or struct_time representing a time as returned by gmtime()
or localtime() to a 24-character string of the following form:
>>> asctime(time.gmtime(0))
'Thu Jan 1 00:00:00 1970'
If t is not provided, the current time as returned by localtime() is used.
Locale information is not used by asctime().
This is meant to normalise the output of the built-in time.asctime() across
different platforms and Python versions.
In Python 3.x, the day of the month is right-justified, whereas on Windows
Python 2.7 it is padded with zeros.
See https://github.com/behdad/fonttools/issues/455
"""
if t is None:
t = time.localtime()
s = "%s %s %2s %s" % (
DAYNAMES[t.tm_wday], MONTHNAMES[t.tm_mon], t.tm_mday,
time.strftime("%H:%M:%S %Y", t))
return s
def gethtml(zurl,str_fname):
mobileEmulation = {'deviceName': 'Apple iPhone 6'}
options = webdriver.ChromeOptions()
options.add_experimental_option('mobileEmulation', mobileEmulation)
driver = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=options)
driver.get(zurl)
time.sleep(5)
result = []
# for i in range(0,300): #???0?20?????i?
for i in range(0, 1): # ???0?3?????i?
print('????' + str(i))
myscroll(driver)
time.sleep(2)
st=time.strftime("%Y%m%d",time.localtime())
# print(driver.page_source, file=open('itg201703.html', 'w', encoding='utf-8'))
print(driver.page_source, file=open(str_fname+"-"+st+".html", 'w', encoding='utf-8'))
print("?????????")
print(driver.title)
driver.quit()
def get_merged_nodes():
merged = {}
mergeddmp = open(args.infile_mergeddmp_path,'r')
for curr_line in mergeddmp:
curr_line_old_taxid = curr_line.split('|')[0].strip()
curr_line_new_taxid = curr_line.split('|')[1].strip()
merged[curr_line_old_taxid] = curr_line_new_taxid
mergeddmp.close()
log_file = open(args.logfile_path, 'a')
log_file.write('get_merged_nodes() finished ' + strftime("%H:%M:%S on %d-%m-%Y",localtime()) + '\n')
log_file.close()
return(merged)
#################################################
def get_deleted_nodes():
deleted = {}
delnodesdmp = open(args.infile_delnodesdmp_path,'r')
for curr_line in delnodesdmp:
curr_line_old_taxid = curr_line.split('|')[0].strip()
deleted[curr_line_old_taxid] = True
delnodesdmp.close()
log_file = open(args.logfile_path, 'a')
log_file.write('get_deleted_nodes() finished ' + strftime("%H:%M:%S on %d-%m-%Y",localtime()) + '\n')
log_file.close()
return(deleted)
#################################################
def print_log(msg, print_flag = True):
"""
Parameters
----------
msg
print_flag
Returns
-------
"""
if print_flag:
if type(msg) is str:
print ('%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()
def main(argv):
dir_ = argv[1]
for entry in sorted(os.listdir(dir_)):
path = os.path.join(dir_, entry)
size = os.path.getsize(path)
mtime = os.path.getmtime(path)
mtime_format = time.strftime("%b %d %H:%M", time.localtime(mtime))
reset = '\033[0m'
if os.path.isdir(path):
color = '\033[1;94m'
elif os.access(path, os.X_OK):
color = '\033[1;92m'
else:
color = ''
senf.print_("%6d %13s %s%s%s" % (size, mtime_format, color,
entry, reset))
def trickit(self,num):
for j in range(num,0,-1):
#self.Label1["text"]=j
minutes = int(j / 60)
seconds = j % 60
label_text = str(minutes) + '??' + str(seconds) + '?'
#self.label["text"]= time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
self.label["text"]= label_text
self.root.update()
time.sleep(1)
self.root.quit
self.root.destroy()
del self.root #?????????????
#test
#screen_saver = ScreenSaver()
#screen_saver.run()
def Time2Internaldate(date_time):
"""'"DD-Mmm-YYYY HH:MM:SS +HHMM"' = Time2Internaldate(date_time)
Convert 'date_time' to IMAP4 INTERNALDATE representation."""
if isinstance(date_time, (int, float)):
tt = time.localtime(date_time)
elif isinstance(date_time, (tuple, time.struct_time)):
tt = date_time
elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
return date_time # Assume in correct format
else:
raise ValueError("date_time not of a known type")
if time.daylight and tt[-1]:
zone = -time.altzone
else:
zone = -time.timezone
return ('"%2d-%s-%04d %02d:%02d:%02d %+03d%02d"' %
((tt[2], MonthNames[tt[1]], tt[0]) + tt[3:6] +
divmod(zone//60, 60)))
def createCsvFile(confFrame):
createCsvDir()
stationName = confFrame.stations[0].stn
prettyDate = time.strftime("%Y%m%d_%H%M%S", time.localtime())
csvFileName = "{}_{}.csv".format(prettyDate, stationName.rstrip())
csv_path = "{}/{}".format(CSV_DIR, csvFileName)
if (os.path.isfile(csv_path)):
nextIndex = getNextIndex(csv_path)
csvFileName = "{}_{}.csv".format(prettyDate, nextIndex)
csv_path = "{}/{}".format(CSV_DIR, csvFileName)
csv_handle = open(csv_path, 'w')
csv_handle.write("Timestamp")
for ch in confFrame.stations[0].channels:
csv_handle.write(",{}".format(ch.rstrip())) if ch.rstrip() != '' else None
csv_handle.write(",Freq")
csv_handle.write(",ROCOF")
csv_handle.write("\n")
return csv_handle
def user_insert(self, nm, pw):
cmd = "SELECT USERNAME, PASSWORD FROM USERS"
map_value = self._db.execute(cmd)
dic = dict(map_value)
if nm in dic.keys():
return None, 1
cmd = "INSERT INTO USERS (USERNAME, PASSWORD, NICKNAME, AVATARNAME) VALUES ('{0}', '{1}', '{2}', '{3}')".format(nm, pw, nm, "")
self._db.execute(cmd)
self._db.commit()
cmd = "SELECT * FROM USERS"
list_value = self._db.execute(cmd)
for ind, name, nickname, avatar_name, password in list_value:
if name == nm:
dic = {"userID": ind, "name": name, "password": password, "nickname": nickname, "avatarName": avatar_name}
current_time = time.localtime()
str_time = time.strftime("%Y-%m-%d %H:%M:%S", current_time)
self.insert_message(SYSTEM_BROADCAST, 0, ind, str_time, "????Paper Melody!!")
return dic, 0
return None, 1
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
# -----------------------------------------------------------------------------
def rst_id(self, rst_id):
"""
Sets the run status of this node.
:param int rst_id: The new run status for this node.
"""
old_rst_id = self.rst_id
self.__rst_id_wrapper(rst_id)
# Update the start datetime of this node.
if rst_id == C.ENK_RST_ID_RUNNING:
if not self._rnd_datetime_start:
self._rnd_datetime_start = strftime("%Y-%m-%d %H:%M:%S", localtime())
self._rnd_datetime_stop = None
# Update the stop datetime of this node.
if old_rst_id != rst_id and rst_id in (C.ENK_RST_ID_COMPLETED, C.ENK_RST_ID_ERROR):
self._rnd_datetime_stop = strftime("%Y-%m-%d %H:%M:%S", localtime())
# ------------------------------------------------------------------------------------------------------------------
def __history_get(self,history,item_ID,time_from,time_till):
'''
????
???? item ??????? history ?
'''
history_data=[]
history_data[:]=[]
response=self.zapi.history.get({
"time_from":time_from,
"time_till":time_till,
"output": "extend",
"history": history,
"itemids": item_ID,
"sortfield":"clock",
"limit": 10080
})
if len(response) == 0:
warn_msg("not have history_data")
debug_info=str([history,item_ID,time_from,time_till,"####not have history_data"])
self.logger.debug(debug_info)
return 0.0
for history_info in response:
timeArray = time.localtime(int(history_info['clock']))
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(item_ID,history_info['value'],otherStyleTime)
def next_time(time_string):
try:
parsed = list(time.strptime(time_string, "%H:%M"))
except (TypeError, ValueError):
return float(time_string)
now = time.localtime()
current = list(now)
current[3:6] = parsed[3:6]
current_time = time.time()
delta = time.mktime(current) - current_time
if delta <= 0.0:
current[2] += 1
return time.mktime(current) - current_time
return delta
def store(self, out, header=""):
""" Write the properties list to the stream 'out' along
with the optional 'header' """
if out.mode[0] != 'w':
raise ValueError('Steam should be opened in write mode!')
try:
#out.write(''.join(('#',header,'\n')))
# Write timestamp
#tstamp = time.strftime('%a %b %d %H:%M:%S %Z %Y', time.localtime())
#out.write(''.join(('#',tstamp,'\n')))
# Write properties from the pristine dictionary
for key, value in sorted(self._origprops.items()):
line = ''.join((key,'=',self.escape(value)))
if not line.endswith('\n'):
line += '\n'
out.write(line)
out.close()
except IOError as e:
raise
def prog(self):#Show progress
nb_batches_total=(self.params['nb_epoch'] if not kv-1 else self.params['epochs'])*self.params['nb_sample']/self.params['batch_size']
nb_batches_epoch=self.params['nb_sample']/self.params['batch_size']
prog_total=(self.t_batches/nb_batches_total if nb_batches_total else 0)+0.01
prog_epoch=(self.c_batches/nb_batches_epoch if nb_batches_epoch else 0)+0.01
if self.t_epochs:
now=time.time()
t_mean=float(sum(self.t_epochs)) / len(self.t_epochs)
eta_t=(now-self.train_start)*((1/prog_total)-1)
eta_e=t_mean*(1-prog_epoch)
t_end=time.asctime(time.localtime(now+eta_t))
e_end=time.asctime(time.localtime(now+eta_e))
m='\nTotal:\nProg:'+str(prog_total*100.)[:5]+'%\nEpoch:'+str(self.epoch[-1])+'/'+str(self.stopped_epoch)+'\nETA:'+str(eta_t)[:8]+'sec\nTrain will be finished at '+t_end+'\nCurrent epoch:\nPROG:'+str(prog_epoch*100.)[:5]+'%\nETA:'+str(eta_e)[:8]+'sec\nCurrent epoch will be finished at '+e_end
self.t_send(m)
print(m)
else:
now=time.time()
eta_t=(now-self.train_start)*((1/prog_total)-1)
eta_e=(now-self.train_start)*((1/prog_epoch)-1)
t_end=time.asctime(time.localtime(now+eta_t))
e_end=time.asctime(time.localtime(now+eta_e))
m='\nTotal:\nProg:'+str(prog_total*100.)[:5]+'%\nEpoch:'+str(len(self.epoch))+'/'+str(self.stopped_epoch)+'\nETA:'+str(eta_t)[:8]+'sec\nTrain will be finished at '+t_end+'\nCurrent epoch:\nPROG:'+str(prog_epoch*100.)[:5]+'%\nETA:'+str(eta_e)[:8]+'sec\nCurrent epoch will be finished at '+e_end
self.t_send(m)
print(m)
def prog(self):#Show progress
nb_batches_total=(self.params['nb_epoch'] if not kv-1 else self.params['epochs'])*self.params['nb_sample']/self.params['batch_size']
nb_batches_epoch=self.params['nb_sample']/self.params['batch_size']
prog_total=(self.t_batches/nb_batches_total if nb_batches_total else 0)+0.01
prog_epoch=(self.c_batches/nb_batches_epoch if nb_batches_epoch else 0)+0.01
if self.t_epochs:
now=time.time()
t_mean=float(sum(self.t_epochs)) / len(self.t_epochs)
eta_t=(now-self.train_start)*((1/prog_total)-1)
eta_e=t_mean*(1-prog_epoch)
t_end=time.asctime(time.localtime(now+eta_t))
e_end=time.asctime(time.localtime(now+eta_e))
m='\nTotal:\nProg:'+str(prog_total*100.)[:5]+'%\nEpoch:'+str(self.epoch[-1])+'/'+str(self.stopped_epoch)+'\nETA:'+str(eta_t)[:8]+'sec\nTrain will be finished at '+t_end+'\nCurrent epoch:\nPROG:'+str(prog_epoch*100.)[:5]+'%\nETA:'+str(eta_e)[:8]+'sec\nCurrent epoch will be finished at '+e_end
self.t_send(m)
print(m)
else:
now=time.time()
eta_t=(now-self.train_start)*((1/prog_total)-1)
eta_e=(now-self.train_start)*((1/prog_epoch)-1)
t_end=time.asctime(time.localtime(now+eta_t))
e_end=time.asctime(time.localtime(now+eta_e))
m='\nTotal:\nProg:'+str(prog_total*100.)[:5]+'%\nEpoch:'+str(len(self.epoch))+'/'+str(self.stopped_epoch)+'\nETA:'+str(eta_t)[:8]+'sec\nTrain will be finished at '+t_end+'\nCurrent epoch:\nPROG:'+str(prog_epoch*100.)[:5]+'%\nETA:'+str(eta_e)[:8]+'sec\nCurrent epoch will be finished at '+e_end
self.t_send(m)
print(m)
def on_train_begin(self, logs={}):
self.epoch=[]
self.t_epochs=[]
self.t_batches=0
self.logs_batches={}
self.logs_epochs={}
self.train_start=time.time()
self.localtime = time.asctime( time.localtime(self.train_start) )
self.mesg = 'Train started at: '+self.localtime
self.t_send(self.mesg)
self.stopped_epoch = (self.params['epochs'] if kv-1 else self.params['nb_epoch'])
#==============================================================================
#==============================================================================
#==============================================================================
#
#==============================================================================
def template_localtime(value, use_tz=None):
"""
Checks if value is a datetime and converts it to local time if necessary.
If use_tz is provided and is not None, that will force the value to
be converted (or not), overriding the value of settings.USE_TZ.
This function is designed for use by the template engine.
"""
should_convert = (isinstance(value, datetime)
and (settings.USE_TZ if use_tz is None else use_tz)
and not is_naive(value)
and getattr(value, 'convert_to_local_time', True))
return localtime(value) if should_convert else value
# Utilities
def localtime(value, timezone=None):
"""
Converts an aware datetime.datetime to local time.
Local time is defined by the current time zone, unless another time zone
is specified.
"""
if timezone is None:
timezone = get_current_timezone()
# If `value` is naive, astimezone() will raise a ValueError,
# so we don't need to perform a redundant check.
value = value.astimezone(timezone)
if hasattr(timezone, 'normalize'):
# This method is available for pytz time zones.
value = timezone.normalize(value)
return value
def log_event(event_tuple):
try:
sec, usec, src_ip, dst_ip = event_tuple[0], event_tuple[1], event_tuple[2], event_tuple[4]
if not any(_ in WHITELIST for _ in (src_ip, dst_ip)):
localtime = "%s.%06d" % (time.strftime(TIME_FORMAT, time.localtime(int(sec))), usec)
event = "%s %s %s\n" % (safe_value(localtime), safe_value(config.SENSOR_NAME), " ".join(safe_value(_) for _ in event_tuple[2:]))
if not config.DISABLE_LOCAL_LOG_STORAGE:
handle = get_event_log_handle(sec)
os.write(handle, event)
if config.LOG_SERVER:
remote_host, remote_port = config.LOG_SERVER.split(':')
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto("%s %s" % (sec, event), (remote_host, int(remote_port)))
if config.DISABLE_LOCAL_LOG_STORAGE and not config.LOG_SERVER:
sys.stdout.write(event)
sys.stdout.flush()
except (OSError, IOError):
if config.SHOW_DEBUG:
traceback.print_exc()
def generate_name():
t = time.localtime()
a = random.choice(['blue', 'yellow', 'green', 'red', 'orange','pink','grey',
'white', 'black', 'turkouse', 'fushia', 'beige','purple',
'rustic', 'idyllic', 'kind', 'turbo', 'feverish','horrid',
'master', 'correct', 'insane', 'relevant','chocolate',
'silk', 'big', 'short', 'cool', 'mighty', 'weak','candid',
'figting','flustered', 'perplexed', 'screaming','hip',
'glorious','magnificent', 'crazy', 'gyrating','sleeping'])
b = random.choice(['battery', 'horse', 'stapler', 'giraff', 'tiger', 'snake',
'cow', 'mouse', 'eagle', 'elephant', 'whale', 'shark',
'house', 'car', 'boat', 'bird', 'plane', 'sea','genius',
'leopard', 'clown', 'matador', 'bull', 'ant','starfish',
'falcon', 'eagle','warthog','fulcrum', 'tank', 'foxbat',
'flanker', 'fullback', 'archer', 'arrow', 'hound'])
datestr = time.strftime("%m%d%H%M%S", t).encode('utf8')
b36 = base36encode(int(datestr))
name = "{}_{}_{}".format(b36,a,b)
return name.upper()
def formatTime(self, when):
"""
Return the given UTC value formatted as a human-readable string
representing that time in the local timezone.
@type when: C{int}
@param when: POSIX timestamp to convert to a human-readable string.
@rtype: C{str}
"""
if self.timeFormat is not None:
return time.strftime(self.timeFormat, time.localtime(when))
tzOffset = -self.getTimezoneOffset()
when = datetime.datetime.utcfromtimestamp(when + tzOffset)
tzHour = int(tzOffset / 60 / 60)
tzMin = int(tzOffset / 60 % 60)
return '%d/%02d/%02d %02d:%02d %+03d%02d' % (
when.year, when.month, when.day,
when.hour, when.minute,
tzHour, tzMin)