Python time.localtime() Examples
The following are 30
code examples of time.localtime().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
time
, or try the search function
.
Example #1
Source File: __init__.py From jawfish with MIT License | 6 votes |
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
Example #2
Source File: helper_functions.py From risk-slim with BSD 3-Clause "New" or "Revised" License | 6 votes |
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()
Example #3
Source File: utils.py From verge3d-blender-addon with GNU General Public License v3.0 | 6 votes |
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. #
Example #4
Source File: GameOfLife.py From BiblioPixelAnimations with MIT License | 6 votes |
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
Example #5
Source File: datetime.py From verge3d-blender-addon with GNU General Public License v3.0 | 6 votes |
def __repr__(self): """Convert to formal string, for repr(). >>> dt = datetime(2010, 1, 1) >>> repr(dt) 'datetime.datetime(2010, 1, 1, 0, 0)' >>> dt = datetime(2010, 1, 1, tzinfo=timezone.utc) >>> repr(dt) 'datetime.datetime(2010, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)' """ return "%s(%d, %d, %d)" % ('datetime.' + self.__class__.__name__, self._year, self._month, self._day) # XXX These shouldn't depend on time.localtime(), because that # clips the usable dates to [1970 .. 2038). At least ctime() is # easily done without using strftime() -- that's better too because # strftime("%c", ...) is locale specific.
Example #6
Source File: sqldb.py From Vxscan with Apache License 2.0 | 6 votes |
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()
Example #7
Source File: sqldb.py From Vxscan with Apache License 2.0 | 6 votes |
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)
Example #8
Source File: password-pwncheck.py From password_pwncheck with MIT License | 6 votes |
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
Example #9
Source File: getmetrics_nfdump.py From InsightAgent with Apache License 2.0 | 6 votes |
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()
Example #10
Source File: cpp.py From SublimeKSP with GNU General Public License v3.0 | 6 votes |
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 # -----------------------------------------------------------------------------
Example #11
Source File: preprocessor_plugins.py From SublimeKSP with GNU General Public License v3.0 | 6 votes |
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) #=================================================================================================
Example #12
Source File: tm1637.py From raspberrypi-examples with MIT License | 6 votes |
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)
Example #13
Source File: pvo_api.py From gw2pvo with MIT License | 6 votes |
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)
Example #14
Source File: summary.py From BatteryMonitor with GNU General Public License v2.0 | 6 votes |
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'])
Example #15
Source File: alarms.py From BatteryMonitor with GNU General Public License v2.0 | 6 votes |
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])
Example #16
Source File: getbms.py From BatteryMonitor with GNU General Public License v2.0 | 6 votes |
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
Example #17
Source File: study_robot.py From 21tb_robot with MIT License | 6 votes |
def log(info): """simple log""" print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), info sys.stdout.flush()
Example #18
Source File: report.py From Vxscan with Apache License 2.0 | 5 votes |
def gener(): out = [] for i in [gen_webinfo(), gen_urls(), gen_ports(), gen_vuln(), gen_crawl()]: if i: out.append(i) result = {"table": out} result = json.dumps(result) result = re.sub(r'^{|}$', '', result) times = time.strftime("%Y%m%d%H%M%S", time.localtime()) name = 'Vxscan_' + times + '.html' with open('report/report.htm', 'r', encoding='utf-8') as f, open(name, 'w') as f1: text = f.read() f1.write(text.replace("'summary': {}", result))
Example #19
Source File: datetime.py From jawfish with MIT License | 5 votes |
def timetuple(self): "Return local time tuple compatible with time.localtime()." dst = self.dst() if dst is None: dst = -1 elif dst: dst = 1 else: dst = 0 return _build_struct_time(self.year, self.month, self.day, self.hour, self.minute, self.second, dst)
Example #20
Source File: api.py From razzy-spinner with GNU General Public License v3.0 | 5 votes |
def run(self): try: self._result = self._command() if self._verbose: print('Thread %s finished with result %s at %s' % \ (self._name, self._result, time.localtime(time.time()))) except Exception as e: print(e) print('Thread %s completed abnormally' % (self._name))
Example #21
Source File: SipLogger.py From rtp_cluster with BSD 2-Clause "Simplified" License | 5 votes |
def ftime(self, ltime): if self.offstime: ltime -= self.itime msec = (ltime % 1) * 1000 if not self.offstime: return '%s.%.3d' % (strftime('%d %b %H:%M:%S', localtime(ltime)), msec) hrs = int(ltime / (60 * 60)) ltime -= (hrs * 60 * 60) mins = int(ltime / 60) ltime -= (mins * 60) secs = int(ltime) return '%.2d:%.2d:%.2d.%.3d' % (hrs, mins, secs, msec)
Example #22
Source File: MonoTime.py From rtp_cluster with BSD 2-Clause "Simplified" License | 5 votes |
def fptime(self, base = None): if base != None: realt = base.realt - (base.monot - self.monot) else: realt = self.realt return '%s.%.3d' % (strftime('%d %b %H:%M:%S', localtime(realt)), \ (realt % 1) * 1000)
Example #23
Source File: config.py From ConvLab with MIT License | 5 votes |
def _init_logging_handler(self): current_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) stderr_handler = logging.StreamHandler() log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'log') if not os.path.exists(log_dir): os.mkdir(log_dir) file_handler = logging.FileHandler(os.path.join(log_dir, 'log_{}.txt').format(current_time)) logging.basicConfig(handlers=[stderr_handler, file_handler]) logger = logging.getLogger() logger.setLevel(logging.DEBUG)
Example #24
Source File: main.py From ConvLab with MIT License | 5 votes |
def init_logging_handler(log_dir, extra=''): if not os.path.exists(log_dir): os.makedirs(log_dir) current_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) stderr_handler = logging.StreamHandler() file_handler = logging.FileHandler('{}/log_{}.txt'.format(log_dir, current_time+extra)) logging.basicConfig(handlers=[stderr_handler, file_handler]) logger = logging.getLogger() logger.setLevel(logging.DEBUG)
Example #25
Source File: utils.py From verge3d-blender-addon with GNU General Public License v3.0 | 5 votes |
def localtime(dt=None, isdst=-1): """Return local time as an aware datetime object. If called without arguments, return current time. Otherwise *dt* argument should be a datetime instance, and it is converted to the local time zone according to the system time zone database. If *dt* is naive (that is, dt.tzinfo is None), it is assumed to be in local time. In this case, a positive or zero value for *isdst* causes localtime to presume initially that summer time (for example, Daylight Saving Time) is or is not (respectively) in effect for the specified time. A negative value for *isdst* causes the localtime() function to attempt to divine whether summer time is in effect for the specified time. """ if dt is None: return datetime.datetime.now(datetime.timezone.utc).astimezone() if dt.tzinfo is not None: return dt.astimezone() # We have a naive datetime. Convert to a (localtime) timetuple and pass to # system mktime together with the isdst hint. System mktime will return # seconds since epoch. tm = dt.timetuple()[:-1] + (isdst,) seconds = time.mktime(tm) localtm = time.localtime(seconds) try: delta = datetime.timedelta(seconds=localtm.tm_gmtoff) tz = datetime.timezone(delta, localtm.tm_zone) except AttributeError: # Compute UTC offset and compare with the value implied by tm_isdst. # If the values match, use the zone name implied by tm_isdst. delta = dt - datetime.datetime(*time.gmtime(seconds)[:6]) dst = time.daylight and localtm.tm_isdst > 0 gmtoff = -(time.altzone if dst else time.timezone) if delta == datetime.timedelta(seconds=gmtoff): tz = datetime.timezone(delta, time.tzname[dst]) else: tz = datetime.timezone(delta) return dt.replace(tzinfo=tz)
Example #26
Source File: server.py From verge3d-blender-addon with GNU General Public License v3.0 | 5 votes |
def log_date_time_string(self): """Return the current time formatted for logging.""" now = time.time() year, month, day, hh, mm, ss, x, y, z = time.localtime(now) s = "%02d/%3s/%04d %02d:%02d:%02d" % ( day, self.monthname[month], year, hh, mm, ss) return s
Example #27
Source File: datetime.py From verge3d-blender-addon with GNU General Public License v3.0 | 5 votes |
def fromtimestamp(cls, t): "Construct a date from a POSIX timestamp (like time.time())." y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t) return cls(y, m, d)
Example #28
Source File: __init__.py From script.module.inputstreamhelper with MIT License | 5 votes |
def info_dialog(self): """ Show an Info box with useful info e.g. for bug reports""" text = localize(30800, version=kodi_version(), system=system_os(), arch=arch()) + '\n' # Kodi information text += '\n' disabled_str = ' ({disabled})'.format(disabled=localize(30054)) ishelper_state = disabled_str if get_setting_bool('disabled', False) else '' istream_state = disabled_str if not self._inputstream_enabled() else '' text += localize(30810, version=addon_version(), state=ishelper_state) + '\n' text += localize(30811, version=self._inputstream_version(), state=istream_state) + '\n' text += '\n' if system_os() == 'Android': text += localize(30820) + '\n' else: from time import localtime, strftime if get_setting_float('last_modified', 0.0): wv_updated = strftime('%Y-%m-%d %H:%M', localtime(get_setting_float('last_modified', 0.0))) else: wv_updated = 'Never' text += localize(30821, version=self._get_lib_version(widevinecdm_path()), date=wv_updated) + '\n' if arch() in ('arm', 'arm64'): # Chrome OS version wv_cfg = load_widevine_config() if wv_cfg: text += localize(30822, name=wv_cfg['hwidmatch'].split()[0].lstrip('^'), version=wv_cfg['version']) + '\n' if get_setting_float('last_check', 0.0): wv_check = strftime('%Y-%m-%d %H:%M', localtime(get_setting_float('last_check', 0.0))) else: wv_check = 'Never' text += localize(30823, date=wv_check) + '\n' text += localize(30824, path=ia_cdm_path()) + '\n' text += '\n' text += localize(30830, url=config.SHORT_ISSUE_URL) # Report issues log(2, '\n{info}'.format(info=kodi_to_ascii(text))) textviewer(localize(30901), text)
Example #29
Source File: ntp.py From glazier with Apache License 2.0 | 5 votes |
def SyncClockToNtp(retries: int = 2, server: Text = 'time.google.com'): """Syncs the hardware clock to an NTP server.""" logging.info('Reading time from NTP server %s.', server) attempts = 0 client = ntplib.NTPClient() response = None while True: try: response = client.request(server, version=3) except (ntplib.NTPException, socket.gaierror) as e: logging.error('NTP client request error: %s', str(e)) if response or attempts >= retries: break logging.info( 'Unable to contact NTP server %s to sync machine clock. This ' 'machine may not have an IP address yet; waiting %d seconds and ' 'trying again. Repeated failure may indicate network or driver ' 'problems.', server, RETRY_DELAY) time.sleep(RETRY_DELAY) attempts += 1 if not response: raise NtpException('No response from NTP server.') local_time = time.localtime(response.ref_time) current_date = time.strftime('%m-%d-%Y', local_time) current_time = time.strftime('%H:%M:%S', local_time) logging.info('Current date/time is %s %s', current_date, current_time) date_set = r'%s\cmd.exe /c date %s' % (WINPE_SYSTEM32, current_date) result = subprocess.call(date_set, shell=True) logging.info('Setting date returned result %s', result) time_set = r'%s\cmd.exe /c time %s' % (WINPE_SYSTEM32, current_time) result = subprocess.call(time_set, shell=True) logging.info('Setting time returned result %s', result)
Example #30
Source File: cd_tools.py From Andromeda with MIT License | 5 votes |
def cd_timestamp_to_time(timestamp, strftime="%Y-%m-%d %H:%M:%S"): """ :param timestamp: 时间戳 :param strftime: 时间格式 :return: 根据时间戳返回格式化时间 """ return time.strftime(strftime, time.localtime(timestamp))