Python time.ctime() Examples
The following are 30
code examples of time.ctime().
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: PyQtPiClock.py From PiClock with MIT License | 6 votes |
def getwx(): global wxurl global wxreply print "getting current and forecast:" + time.ctime() wxurl = 'https://api.darksky.net/forecast/' + \ ApiKeys.dsapi + \ '/' wxurl += str(Config.location.lat) + ',' + \ str(Config.location.lng) wxurl += '?units=us&lang=' + Config.Language.lower() wxurl += '&r=' + str(random.random()) print wxurl r = QUrl(wxurl) r = QNetworkRequest(r) wxreply = manager.get(r) wxreply.finished.connect(wxfinished)
Example #2
Source File: mmbot.py From MaliciousMacroBot with MIT License | 6 votes |
def get_file_meta_data(self, filepath, filename=None, getHash=False): """ helper function to get meta information about a file to include it's path, date modified, size :param filepath: path to a file :param filename: filename :param getHash: whether or not the hash should be computed :return: a tuple of format (filename, filepath, filesize, filemodified, md5) """ if filename is None: filename = os.path.split(filepath)[1] filemodified = time.ctime(os.path.getmtime(filepath)) filesize = os.path.getsize(filepath) md5 = np.nan if getHash: md5 = self.get_file_hash(filepath) return (filename, filepath, filesize, filemodified, md5)
Example #3
Source File: weka.py From razzy-spinner with GNU General Public License v3.0 | 6 votes |
def header_section(self): """Returns an ARFF header as a string.""" # Header comment. s = ('% Weka ARFF file\n' + '% Generated automatically by NLTK\n' + '%% %s\n\n' % time.ctime()) # Relation name s += '@RELATION rel\n\n' # Input attribute specifications for fname, ftype in self._features: s += '@ATTRIBUTE %-30r %s\n' % (fname, ftype) # Label attribute specification s += '@ATTRIBUTE %-30r {%s}\n' % ('-label-', ','.join(self._labels)) return s
Example #4
Source File: xls.py From rekall with GNU General Public License v2.0 | 6 votes |
def __init__(self, output=None, **kwargs): super(XLSRenderer, self).__init__(**kwargs) # Make a single delegate text renderer for reuse. Most of the time we # will just replicate the output from the TextRenderer inside the # spreadsheet cell. self.delegate_text_renderer = text.TextRenderer(session=self.session) self.output = output or self.session.GetParameter("output") # If no output filename was give, just make a name based on the time # stamp. if self.output == None: self.output = "%s.xls" % time.ctime() try: self.wb = openpyxl.load_workbook(self.output) self.current_ws = self.wb.create_sheet() except IOError: self.wb = openpyxl.Workbook() self.current_ws = self.wb.active
Example #5
Source File: chunkparser_app.py From razzy-spinner with GNU General Public License v3.0 | 6 votes |
def save_grammar(self, filename=None): if not filename: ftypes = [('Chunk Gramamr', '.chunk'), ('All files', '*')] filename = tkinter.filedialog.asksaveasfilename(filetypes=ftypes, defaultextension='.chunk') if not filename: return if (self._history and self.normalized_grammar == self.normalize_grammar(self._history[-1][0])): precision, recall, fscore = ['%.2f%%' % (100*v) for v in self._history[-1][1:]] elif self.chunker is None: precision = recall = fscore = 'Grammar not well formed' else: precision = recall = fscore = 'Not finished evaluation yet' with open(filename, 'w') as outfile: outfile.write(self.SAVE_GRAMMAR_TEMPLATE % dict( date=time.ctime(), devset=self.devset_name, precision=precision, recall=recall, fscore=fscore, grammar=self.grammar.strip()))
Example #6
Source File: benchmark_cnn.py From benchmarks with Apache License 2.0 | 6 votes |
def run(self): while self.finish_time == 0: time.sleep(.25) global_step_val, = self.sess.run([self.global_step_op]) if self.start_time == 0 and global_step_val >= self.start_at_global_step: # Use tf.logging.info instead of log_fn, since print (which is log_fn) # is not thread safe and may interleave the outputs from two parallel # calls to print, which can break tests. tf.logging.info('Starting real work at step %s at time %s' % (global_step_val, time.ctime())) self.start_time = time.time() self.start_step = global_step_val if self.finish_time == 0 and global_step_val >= self.end_at_global_step: tf.logging.info('Finishing real work at step %s at time %s' % (global_step_val, time.ctime())) self.finish_time = time.time() self.finish_step = global_step_val
Example #7
Source File: 4_thread_fac_fib.py From deep-learning-note with MIT License | 6 votes |
def main(): nfuncs = range(len(funcs)) print('*** 单线程') for i in nfuncs: print('starting', funcs[i].__name__, 'at:', ctime()) print(funcs[i](n)) print(funcs[i].__name__, 'finished at:', ctime()) print('\n*** 多线程') threads = [] for i in nfuncs: t = MyThread(funcs[i], (n,), funcs[i].__name__) threads.append(t) for i in nfuncs: threads[i].start() for i in nfuncs: threads[i].join() print(threads[i].getResult()) print('ALL DONE')
Example #8
Source File: 2_thread_wayA.py From deep-learning-note with MIT License | 6 votes |
def main(): print('程序开始,当前时间', ctime()) threads = [] nloops = range(len(loops)) for i in nloops: t = threading.Thread(target=loop, args=(i, loops[i])) threads.append(t) for i in nloops: threads[i].start() for i in nloops: threads[i].join() # 等待进程完成 print('程序结束,当前时间', ctime())
Example #9
Source File: fig19_15.py From PythonClassBook with GNU General Public License v3.0 | 6 votes |
def run( self ): """Vehicle waits unless/until light is green""" # stagger arrival times time.sleep( random.randrange( 1, 10 ) ) # prints arrival time of car at intersection print "%s arrived at %s" % \ ( self.getName(), time.ctime( time.time() ) ) # wait for green light self.threadEvent.wait() # displays time that car departs intersection print "%s passes through intersection at %s" % \ ( self.getName(), time.ctime( time.time() ) )
Example #10
Source File: main.py From crawler_examples with Apache License 2.0 | 6 votes |
def crawl(url): """ 从给定的URL中提取出内容,并以列表的形式返回。 """ try: html = requests.get(url) except: with open("log.log","a") as file: file.write("Http error on " + time.ctime()) time.sleep(60) return None soup = BeautifulSoup(html.text, 'lxml') data_list = [] for cont in soup.find_all("div", {"class":"content"}): raw_data = cont.get_text() data = raw_data.replace("\n","") data_list.append(data) return data_list
Example #11
Source File: __init__.py From asn1tools with MIT License | 6 votes |
def generate(compiled, codec): """Generate Rust source code from given compiled specification. """ date = time.ctime() if codec == 'uper': helpers, types_code = uper.generate(compiled) else: raise Exception() source = SOURCE_FMT.format(version=__version__, date=date, helpers=helpers, types_code=types_code) return source
Example #12
Source File: 3_thread_wayB.py From deep-learning-note with MIT License | 6 votes |
def main(): print('程序开始,当前时间', ctime()) threads = [] nloops = range(len(loops)) for i in nloops: t = MyThread(loop, (i, loops[i])) threads.append(t) for i in nloops: threads[i].start() for i in nloops: threads[i].join() # 等待进程完成 print('程序结束,当前时间', ctime())
Example #13
Source File: pstats.py From meddle with MIT License | 6 votes |
def load_stats(self, arg): if not arg: self.stats = {} elif isinstance(arg, basestring): f = open(arg, 'rb') self.stats = marshal.load(f) f.close() try: file_stats = os.stat(arg) arg = time.ctime(file_stats.st_mtime) + " " + arg except: # in case this is not unix pass self.files = [ arg ] elif hasattr(arg, 'create_stats'): arg.create_stats() self.stats = arg.stats arg.stats = {} if not self.stats: raise TypeError, "Cannot create or construct a %r object from '%r''" % ( self.__class__, arg) return
Example #14
Source File: generator.py From meddle with MIT License | 6 votes |
def flatten(self, msg, unixfrom=False): """Print the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard' one is crafted. By default, this is False to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed. """ if unixfrom: ufrom = msg.get_unixfrom() if not ufrom: ufrom = 'From nobody ' + time.ctime(time.time()) print >> self._fp, ufrom self._write(msg)
Example #15
Source File: Logger.py From StructEngPy with MIT License | 6 votes |
def info(log:str,target='console'): """ log: text to record. target: 'console' to print log on screen or file to write in. """ if target=='console': thd=threading.Thread(target=print,args=(ctime(),':',log)) thd.setDaemon(True) thd.start() thd.join() else: try: thd=threading.Thread(target=print,args=(ctime(),':',log)) thd.setDaemon(True) thd.start() thd.join() except Exception as e: print(e)
Example #16
Source File: BinaryClock.py From BiblioPixelAnimations with MIT License | 6 votes |
def step(self, amt=1): self.layout.all_off() a = "" + time.ctime() tIndex = [11, 12, 14, 15, 17, 18] colSize = [2, 4, 3, 4, 3, 4] for x in range(6): b = bin(128 + int(a[tIndex[x]])) for i in range(colSize[x]): is_off = b[6 + (4 - colSize[x]) + i] == '0' color = self.palette(int(is_off)) self.layout.fillRect( self._origX + (x) + (self._lightSize - 1) * x + self._colSpacing * x, ((4 - colSize[x]) + i + self._origY) * self._lightSize, self._lightSize, self._lightSize, color)
Example #17
Source File: calc.py From aospy with Apache License 2.0 | 6 votes |
def load(self, dtype_out_time, dtype_out_vert=False, region=False, plot_units=False, mask_unphysical=False): """Load the data from the object if possible or from disk.""" msg = ("Loading data from disk for object={0}, dtype_out_time={1}, " "dtype_out_vert={2}, and region=" "{3}".format(self, dtype_out_time, dtype_out_vert, region)) logging.info(msg + ' ({})'.format(ctime())) # Grab from the object if its there. try: data = self.data_out[dtype_out_time] except (AttributeError, KeyError): # Otherwise get from disk. Try scratch first, then archive. try: data = self._load_from_disk(dtype_out_time, dtype_out_vert, region=region) except IOError: data = self._load_from_tar(dtype_out_time, dtype_out_vert) # Copy the array to self.data_out for ease of future access. self._update_data_out(data, dtype_out_time) # Apply desired plotting/cleanup methods. if mask_unphysical: data = self.var.mask_unphysical(data) if plot_units: data = self.var.to_plot_units(data, dtype_vert=dtype_out_vert) return data
Example #18
Source File: Templates.py From pcocc with GNU General Public License v3.0 | 5 votes |
def display(self): if self.placeholder: raise InvalidConfigurationError('restricted template name') tbl = TextTable("%attribute %inherited %value") tbl.header_labels = {'attribute': 'attribute', 'inherited': 'inherited', 'value': 'value'} for setting in template_settings: _, default, _ = template_settings[setting] # Dont show settings with default value if not setting in self.settings and getattr(self, setting) == default: continue if setting in self.settings: inherited = 'No' else: inherited = 'Yes' value = str(getattr(self, setting)) tbl.append({'attribute': setting, 'inherited': inherited, 'value': value}) try: image_file, revision = self.resolve_image() tbl.append({'attribute': 'image-revision', 'inherited': 'No', 'value': '%d (%s)' % (revision, time.ctime( os.path.getmtime(image_file)))}) except: tbl.append({'attribute': 'image-revision', 'inherited': 'No', 'value': 'N/A'}) print tbl
Example #19
Source File: comicbooks.py From Lector with GNU General Public License v3.0 | 5 votes |
def generate_metadata(self): title = os.path.basename(self.book_extension[0]).strip(' ') author = '<Unknown>' isbn = None tags = [] cover = self.book.read(self.image_list[0]) creation_time = time.ctime(os.path.getctime(self.filename)) year = creation_time.split()[-1] Metadata = collections.namedtuple( 'Metadata', ['title', 'author', 'year', 'isbn', 'tags', 'cover']) return Metadata(title, author, year, isbn, tags, cover)
Example #20
Source File: file_infos.py From knmt with GNU General Public License v3.0 | 5 votes |
def create_filename_infos(model_filename): model_infos = OrderedNamespace() model_infos["path"] = model_filename model_infos["last_modif"] = time.ctime(os.path.getmtime(model_filename)) model_infos["hash"] = compute_hash_of_file(model_filename) return model_infos
Example #21
Source File: PySourceColor.py From mishkal with GNU General Public License v3.0 | 5 votes |
def _getDocumentCreatedBy(self): return '<!--This document created by %s ver.%s on: %s-->\n'%( __title__,__version__,time.ctime()) ################################################### HTML markup functions
Example #22
Source File: run.py From Python-Tensorflow-Face-v2.0 with Apache License 2.0 | 5 votes |
def get_row_train_data(train_step, saver, step, train_data, num): loss_step = 0 # 代表进行loss训练的第几批 loss_step = step_i / batch_size losses = 0 # 总的loss初始化为0 image_x1 = [] image_x2 = [] image_x3 = [] # 每次取(batch_size)张图片 for step_i, data in enumerate(train_data): if step_i > 1 and step_i % batch_size == 0: loss_step += 1 if loss_step >= 00: train_anc = np.array(image_x1) train_pos = np.array(image_x2) train_neg = np.array(image_x3) _, loss_v = sess.run([train_step, siamese.loss], feed_dict={ siamese.x1: train_anc, siamese.x2: train_pos, siamese.x3: train_neg, siamese.keep_f: 1.0}) losses = losses + loss_v print('time %s step %d, %d: loss %.4f losses %.4f' % (ctime(), step, loss_step, loss_v, losses)) # if loss_step % 10 == 0 : # saver.save(sess, model_file) # print('保存成功') image_x1.clear() image_x2.clear() image_x3.clear() x1 = data[0] x2 = data[1] x3 = data[2] image_x1.append(my_api.Random.get_image_array(x1)) image_x2.append(my_api.Random.get_image_array(x2)) image_x3.append(my_api.Random.get_image_array(x3)) return losses
Example #23
Source File: PySourceColor.py From mishkal with GNU General Public License v3.0 | 5 votes |
def _doXHTMLFooter(self): # Optional if self.footer: self.out.write('%s\n'%self.footer) else: self.out.write('<hr/><div class="%s"># %s <br/> \ # %s</div>\n'%(MARKUPDICT.get(NAME), self.title, time.ctime()))
Example #24
Source File: messages.py From checklocktimeverify-demos with GNU General Public License v3.0 | 5 votes |
def __repr__(self): return "msg_version(nVersion=%i nServices=%i nTime=%s addrTo=%s addrFrom=%s nNonce=0x%016X strSubVer=%s nStartingHeight=%i)" % (self.nVersion, self.nServices, time.ctime(self.nTime), repr(self.addrTo), repr(self.addrFrom), self.nNonce, self.strSubVer, self.nStartingHeight)
Example #25
Source File: messages.py From checklocktimeverify-demos with GNU General Public License v3.0 | 5 votes |
def __repr__(self): return "msg_version(nVersion=%i nServices=%i nTime=%s addrTo=%s addrFrom=%s nNonce=0x%016X strSubVer=%s nStartingHeight=%i)" % (self.nVersion, self.nServices, time.ctime(self.nTime), repr(self.addrTo), repr(self.addrFrom), self.nNonce, self.strSubVer, self.nStartingHeight)
Example #26
Source File: views.py From don with Apache License 2.0 | 5 votes |
def get_data(self): data = api.list_collection(self.request) for item in data: item['timestamp'] = str(time.ctime(float(item.get('timestamp')))) return data
Example #27
Source File: comment_email_milter.py From pagure with GNU General Public License v2.0 | 5 votes |
def envfrom(self, mailfrom, *str): self.log("mail from: %s - %s" % (mailfrom, str)) self.fromparms = Milter.dictfromlist(str) # NOTE: self.fp is only an *internal* copy of message data. You # must use addheader, chgheader, replacebody to change the message # on the MTA. self.fp = BytesIO() self.canon_from = "@".join(parse_addr(mailfrom)) from_txt = "From %s %s\n" % (self.canon_from, time.ctime()) self.fp.write(from_txt.encode("utf-8")) return Milter.CONTINUE
Example #28
Source File: StataImproved.py From StataImproved with MIT License | 5 votes |
def run(self, edit): sel = self.view.sel(); for s in sel: self.view.replace(edit, s, time.ctime())
Example #29
Source File: gftools-build-vf.py From gftools with Apache License 2.0 | 5 votes |
def intro(): """ Gives basic script info. """ printG("# # ##### ##### ################") printG("# # # # # # ## #") printG(" # # #### # # # # # #######") printG(" # # # <----> # ## # # #") printG(" ## # # # # ####") printG(" ## # ########## #####") print("\n**** Starting variable font build script:") print(" [+]", time.ctime()) printG(" [!] Done")
Example #30
Source File: AnnotatedCommand.py From llvm-zorg with Apache License 2.0 | 5 votes |
def fixupLast(self, status=None): # Potentially start initial section here, as initial section might have # no output at all. self.initialSection() last = self.sections[-1] # Update status if set as an argument. if status is not None: last['status'] = status # Final update of text. self.updateText() # Add timing info. (start, end) = self.command.step_status.getTimes() msg = '\n\n' + '-' * 80 + '\n' if start is None: msg += 'Not Started\n' else: if end is None: end = util.now() msg += '\n'.join([ 'started: %s' % time.ctime(start), 'ended: %s' % time.ctime(end), 'duration: %s' % util.formatInterval(end - start), '', # So we get a final \n ]) last['log'].addStdout(msg) # Change status (unless handling the preamble). if len(self.sections) != 1: last['step'].stepFinished(last['status']) # Finish log. last['log'].finish()