python类localtime()的实例源码

logger.py 文件源码 项目:KerbalPie 作者: Vivero 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
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")
logger.py 文件源码 项目:KerbalPie 作者: Vivero 项目源码 文件源码 阅读 43 收藏 0 点赞 0 评论 0
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))
__init__.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
netkeeper.py 文件源码 项目:Netkeeper 作者: 1941474711 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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("?????????????")

    # ????????
Utils.py 文件源码 项目:Auto_Analysis 作者: ztwo 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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'))
        );""")
integration.py 文件源码 项目:Auto_Analysis 作者: ztwo 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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
F-Scrack.py 文件源码 项目:F-Scrack 作者: y1ng1996 项目源码 文件源码 阅读 41 收藏 0 点赞 0 评论 0
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()
timeTools.py 文件源码 项目:otRebuilder 作者: Pal3love 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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
test.py 文件源码 项目:readwx 作者: xocom 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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()
entrez_qiime.py 文件源码 项目:entrez_qiime 作者: bakerccm 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)

#################################################
entrez_qiime.py 文件源码 项目:entrez_qiime 作者: bakerccm 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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)

#################################################
helper_functions.py 文件源码 项目:risk-slim 作者: ustunb 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
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()
ls.py 文件源码 项目:senf 作者: quodlibet 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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))
screensave.py 文件源码 项目:RestReminder 作者: JerrellGuo 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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()
imaplib2.py 文件源码 项目:sndlatr 作者: Schibum 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)))
pmuToCsv.py 文件源码 项目:PyMU 作者: ITI 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
database.py 文件源码 项目:Paper-Melody.server 作者: gigaflw 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
cpp.py 文件源码 项目:noc-orchestrator 作者: DirceuSilvaLabs 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
    # -----------------------------------------------------------------------------
Node.py 文件源码 项目:py-enarksh 作者: SetBased 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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())

    # ------------------------------------------------------------------------------------------------------------------
zabbix_api.py 文件源码 项目:zabbix_manager 作者: BillWang139967 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
mailer.py 文件源码 项目:abusehelper 作者: Exploit-install 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
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
pyjavaproperties.py 文件源码 项目:properties-editor 作者: dominikgiermala 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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
main.8.7.py 文件源码 项目:Keras_FB 作者: InvidHead 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
main.8.6.py 文件源码 项目:Keras_FB 作者: InvidHead 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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)
main.8.5.py 文件源码 项目:Keras_FB 作者: InvidHead 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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'])
#==============================================================================

#==============================================================================

#==============================================================================
#     
#==============================================================================
timezone.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
timezone.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
log.py 文件源码 项目:malware 作者: JustF0rWork 项目源码 文件源码 阅读 52 收藏 0 点赞 0 评论 0
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()
common_funs.py 文件源码 项目:identifiera-sarkasm 作者: risnejunior 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
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()
log.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号