本文整理汇总了Python中time.localtime方法的典型用法代码示例。如果您正苦于以下问题:Python time.localtime方法的具体用法?Python time.localtime怎么用?Python time.localtime使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类time
的用法示例。
在下文中一共展示了time.localtime方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_time_table
# 需要导入模块: import time [as 别名]
# 或者: from time import localtime [as 别名]
def create_time_table(self, t):
t = time.localtime(t)
hr = t.tm_hour
if not self.mil_time:
hr = hr % 12
hrs = str(hr).zfill(2)
mins = str(t.tm_min).zfill(2)
val = hrs + ":" + mins
w, h = font.str_dim(val, font=self.font_name,
font_scale=self.scale, final_sep=False)
x = (self.width - w) // 2
y = (self.height - h) // 2
old_buf = copy.copy(self.layout.colors)
self.layout.all_off()
self.layout.drawText(val, x, y, color=COLORS.Red,
font=self.font_name, font_scale=self.scale)
table = []
for y in range(self.height):
table.append([0] * self.width)
for x in range(self.width):
table[y][x] = int(any(self.layout.get(x, y)))
self.layout.setBuffer(old_buf)
return table
示例2: getFileNameList
# 需要导入模块: import time [as 别名]
# 或者: from time import localtime [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()
示例3: __init__
# 需要导入模块: import time [as 别名]
# 或者: from time import localtime [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
# -----------------------------------------------------------------------------
示例4: createBuiltinDefines
# 需要导入模块: import time [as 别名]
# 或者: from time import localtime [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)
#=================================================================================================
示例5: add_status
# 需要导入模块: import time [as 别名]
# 或者: from time import localtime [as 别名]
def add_status(self, pgrid_w, eday_kwh, temperature, voltage):
t = time.localtime()
payload = {
'd' : "{:04}{:02}{:02}".format(t.tm_year, t.tm_mon, t.tm_mday),
't' : "{:02}:{:02}".format(t.tm_hour, t.tm_min),
'v1' : round(eday_kwh * 1000),
'v2' : round(pgrid_w)
}
if temperature is not None:
payload['v5'] = temperature
if voltage is not None:
payload['v6'] = voltage
self.call("https://pvoutput.org/service/r2/addstatus.jsp", payload)
示例6: __init__
# 需要导入模块: import time [as 别名]
# 或者: from time import localtime [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'])
示例7: scanalarms
# 需要导入模块: import time [as 别名]
# 或者: from time import localtime [as 别名]
def scanalarms(self,batdata):
# self.timedate = localtime()
# print (self.timedate.tm_hour)
for i in config['alarms']:
if not self.alarmtriggered[i]:
exec(config['alarms'][i][1])
# log.debug('{}{}{}'.format(self.test,batdata.maxcellv,batdata.lastmaxcellv))
if self.test:
# sys.stderr.write('Alarm 1 triggered')
log.info('alarm {} triggered'.format(i))
self.alarmtriggered[i]=True
exec(config['alarms'][i][2])
if self.alarmtriggered[i]:
exec(config['alarms'][i][3])
if self.test:
log.info('alarm {} reset'.format(i))
self.alarmtriggered[i]=False
exec(config['alarms'][i][4])
示例8: getbmsdat
# 需要导入模块: import time [as 别名]
# 或者: from time import localtime [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
示例9: clock
# 需要导入模块: import time [as 别名]
# 或者: from time import localtime [as 别名]
def clock(self, military_time):
"""Clock script modified from:
https://github.com/johnlr/raspberrypi-tm1637"""
self.ShowDoublepoint(True)
while (not self.__stop_event.is_set()):
t = localtime()
hour = t.tm_hour
if not military_time:
hour = 12 if (t.tm_hour % 12) == 0 else t.tm_hour % 12
d0 = hour // 10 if hour // 10 else 0
d1 = hour % 10
d2 = t.tm_min // 10
d3 = t.tm_min % 10
digits = [d0, d1, d2, d3]
self.Show(digits)
# # Optional visual feedback of running alarm:
# print digits
# for i in tqdm(range(60 - t.tm_sec)):
for i in range(60 - t.tm_sec):
if (not self.__stop_event.is_set()):
sleep(1)
示例10: logmsg
# 需要导入模块: import time [as 别名]
# 或者: from time import localtime [as 别名]
def logmsg(request,type,message,args):
is_dst = time.daylight and time.localtime().tm_isdst > 0
tz = - (time.altzone if is_dst else time.timezone) / 36
if tz>=0:
tz="+%04d"%tz
else:
tz="%05d"%tz
datestr = '%d/%b/%Y %H:%M:%S'
user = getattr(logStore,'user','')
isValid = getattr(logStore,'isValid','')
code = getattr(logStore,'code','')
args = getLogDateTime(args)
log = '%s %s,%s,%s,%s,%s,%s' % (datetime.now().strftime(datestr),tz,request.address_string(),user,isValid,code, message % args)
with logLock:
with open(cfg.logpath,'a') as fw:
fw.write(log+os.linesep)
return log
示例11: formatTime
# 需要导入模块: import time [as 别名]
# 或者: from time import localtime [as 别名]
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(self.default_time_format, ct)
s = self.default_msec_format % (t, record.msecs)
return s
示例12: get_ports
# 需要导入模块: import time [as 别名]
# 或者: from time import localtime [as 别名]
def get_ports(self, ipaddr, ports):
self.create_ports()
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
for i in ports:
service = i.get('server')
port = i.get('port')
banner = i.get('banner')
banner = re.sub('<', '', banner)
banner = re.sub('>', '', banner)
md5sum = hashlib.md5()
strings = str(ipaddr) + str(service) + str(port)
md5sum.update(strings.encode('utf-8'))
md5 = md5sum.hexdigest()
values = (timestamp, ipaddr, service, port, banner, md5)
query = "INSERT OR IGNORE INTO ports (time, ipaddr, service, port, banner,md5) VALUES (?,?,?,?,?,?)"
self.insert_ports(query, values)
示例13: get_crawl
# 需要导入模块: import time [as 别名]
# 或者: from time import localtime [as 别名]
def get_crawl(self, domain, crawl):
self.create_crawl()
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
for i in crawl:
if 'Dynamic:' in i:
type = 'Dynamic link'
else:
type = 'Leaks'
md5sum = hashlib.md5()
try:
text = re.search(r'(?<=Email: ).*|(?<=Phone: ).*', i).group()
except:
text = str(i)
strings = str(domain) + text
md5sum.update(strings.encode('utf-8'))
md5 = md5sum.hexdigest()
values = (timestamp, domain, type, i, md5)
query = "INSERT OR IGNORE INTO Crawl (time, domain, type, leaks, md5) VALUES (?,?,?,?,?)"
self.insert_crawl(query, values)
self.commit()
self.close()
示例14: print_log
# 需要导入模块: import time [as 别名]
# 或者: from time import localtime [as 别名]
def print_log(msg, print_flag = True):
"""
Parameters
----------
msg
print_flag
Returns
-------
"""
if print_flag:
if isinstance(msg, str):
print('%s | %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()
示例15: collapse_rfc2231_value
# 需要导入模块: import time [as 别名]
# 或者: from time import localtime [as 别名]
def collapse_rfc2231_value(value, errors='replace',
fallback_charset='us-ascii'):
if not isinstance(value, tuple) or len(value) != 3:
return unquote(value)
# While value comes to us as a unicode string, we need it to be a bytes
# object. We do not want bytes() normal utf-8 decoder, we want a straight
# interpretation of the string as character bytes.
charset, language, text = value
rawbytes = bytes(text, 'raw-unicode-escape')
try:
return str(rawbytes, charset, errors)
except LookupError:
# charset is not a known codec.
return unquote(text)
#
# datetime doesn't provide a localtime function yet, so provide one. Code
# adapted from the patch in issue 9527. This may not be perfect, but it is
# better than not having it.
#