Python time.localtime() Examples

The following are code examples for showing how to use time.localtime(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
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 
Example 2
Project: pyblish-win   Author: pyblish   File: test_strftime.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _update_variables(self, now):
        # we must update the local variables on every cycle
        self.gmt = time.gmtime(now)
        now = time.localtime(now)

        if now[3] < 12: self.ampm='(AM|am)'
        else: self.ampm='(PM|pm)'

        self.jan1 = time.localtime(time.mktime((now[0], 1, 1, 0, 0, 0, 0, 1, 0)))

        try:
            if now[8]: self.tz = time.tzname[1]
            else: self.tz = time.tzname[0]
        except AttributeError:
            self.tz = ''

        if now[3] > 12: self.clock12 = now[3] - 12
        elif now[3] > 0: self.clock12 = now[3]
        else: self.clock12 = 12

        self.now = now 
Example 3
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_timezone(self):
        # Test timezone directives.
        # When gmtime() is used with %Z, entire result of strftime() is empty.
        # Check for equal timezone names deals with bad locale info when this
        # occurs; first found in FreeBSD 4.4.
        strp_output = _strptime._strptime_time("UTC", "%Z")
        self.assertEqual(strp_output.tm_isdst, 0)
        strp_output = _strptime._strptime_time("GMT", "%Z")
        self.assertEqual(strp_output.tm_isdst, 0)
        time_tuple = time.localtime()
        strf_output = time.strftime("%Z")  #UTC does not have a timezone
        strp_output = _strptime._strptime_time(strf_output, "%Z")
        locale_time = _strptime.LocaleTime()
        if time.tzname[0] != time.tzname[1] or not time.daylight:
            self.assertTrue(strp_output[8] == time_tuple[8],
                            "timezone check failed; '%s' -> %s != %s" %
                             (strf_output, strp_output[8], time_tuple[8]))
        else:
            self.assertTrue(strp_output[8] == -1,
                            "LocaleTime().timezone has duplicate values and "
                             "time.daylight but timezone value not set to -1") 
Example 4
Project: pyblish-win   Author: pyblish   File: pickletester.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_structseq(self):
        import time
        import os

        t = time.localtime()
        for proto in protocols:
            s = self.dumps(t, proto)
            u = self.loads(s)
            self.assertEqual(t, u)
            if hasattr(os, "stat"):
                t = os.stat(os.curdir)
                s = self.dumps(t, proto)
                u = self.loads(s)
                self.assertEqual(t, u)
            if hasattr(os, "statvfs"):
                t = os.statvfs(os.curdir)
                s = self.dumps(t, proto)
                u = self.loads(s)
                self.assertEqual(t, u)

    # Tests for protocol 2 
Example 5
Project: core   Author: lifemapper   File: server.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, user_id, gridset_name, success_file):
        """Construct the command object

        Args:
            user_id: User for the gridset
            gridset_name: The unique gridset name
        """
        _LmServerCommand.__init__(self)
        
        # file ends up in LOG_PATH
        secs = time.time()
        timestamp = "{}".format(time.strftime("%Y%m%d-%H%M", time.localtime(secs)))
        logname = '{}.{}'.format(self.scriptBasename, timestamp)
            
        # Required args
        self.args = '{} {} {}'.format(user_id, gridset_name, success_file)
        # Optional arg, we also want for output 
        self.opt_args += ' --logname={}'.format(logname)

        self.outputs.append(success_file)
#         # Logfile is created by script in LOG_DIR
#         logfilename = '{}{}'.format(logname, LMFormat.LOG.ext)
#         self.outputs.append(logfilename)
            
# ............................................................................. 
Example 6
Project: core   Author: lifemapper   File: initWorkflow.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, paramFname, logname=None):
        """
        @summary Constructor for BOOMFiller class.
        """
        super(BOOMFiller, self).__init__()

        scriptname, _ = os.path.splitext(os.path.basename(__file__))
        self.name = scriptname
        if logname is None:
            import time
            secs = time.time()
            timestamp = "{}".format(time.strftime("%Y%m%d-%H%M", time.localtime(secs)))
            logname = '{}.{}'.format(scriptname, timestamp)
        self.logname = logname
                
        self.inParamFname = paramFname
        # Get database
        try:
            self.scribe = self._getDb(self.logname)
        except: 
            raise
        self.open()

    # ............................................... 
Example 7
Project: core   Author: lifemapper   File: boomPost.py    GNU General Public License v3.0 6 votes vote down vote up
def init_boom(self):
        """Initializes the BOOM by writing the file and calling BOOMFiller
        """
        filename = self._get_temp_filename(
            LMFormat.PARAMS.ext, prefix='boom_config_')
            
        with open(filename, 'w') as configOutF:
            self.config.write(configOutF)
            
        import time
        scriptname, _ = os.path.splitext(os.path.basename(__file__))
        secs = time.time()
        timestamp = "{}".format(
            time.strftime("%Y%m%d-%H%M", time.localtime(secs)))
        logname = '{}.{}'.format(scriptname, timestamp)
        
        filler = BOOMFiller(filename, logname=logname)
        gridset = filler.initBoom()
        
        return gridset 
Example 8
Project: helloworld   Author: pip-uninstaller-python   File: 河北.py    GNU General Public License v2.0 6 votes vote down vote up
def get_detail(id):
    data={
        'id': id
    }
    res=requests.post(post_url,data=data,verify=False).text
    title=re.search(r'"title":"(.*?)"',res)[1]
    print(title)
    hit = re.search(r'"hit":(\d+)',res)[1]
    print(hit)
    da= re.search(r'"createDate":(\d+)',res)[1]
    ctime=time.localtime(int(int(da)//1000))#采集的为时间戳,切X1000了要还原 再解析
    otherStyleTime = time.strftime("%Y--%m--%d %H:%M:%S", ctime)
    print(otherStyleTime)
    content=re.search(r'"content":"(.*?)",',res)[1]
    content=re.sub(r'<p style=\\"text-indent:2em;\\">|\\r|\\n|\\t|</p>|<p align=(.*?)>|<img alt=(.*?)>','',content)
    print(content)
    item=[title,hit,data,content]
    return item 
Example 9
Project: 21tb_robot   Author: iloghyr   File: study_robot.py    MIT License 5 votes vote down vote up
def log(info):
    """simple log"""
    print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), info
    sys.stdout.flush() 
Example 10
Project: pyblish-win   Author: pyblish   File: imaplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _mesg(self, s, secs=None):
            if secs is None:
                secs = time.time()
            tm = time.strftime('%M:%S', time.localtime(secs))
            sys.stderr.write('  %s.%02d %s\n' % (tm, (secs*100)%100, s))
            sys.stderr.flush() 
Example 11
Project: pyblish-win   Author: pyblish   File: imaplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def Time2Internaldate(date_time):

    """Convert date_time to IMAP4 INTERNALDATE representation.

    Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'.  The
    date_time argument can be a number (int or float) representing
    seconds since epoch (as returned by time.time()), a 9-tuple
    representing local time (as returned by time.localtime()), or a
    double-quoted string.  In the last case, it is assumed to already
    be in the correct format.
    """

    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")

    dt = time.strftime("%d-%b-%Y %H:%M:%S", tt)
    if dt[0] == '0':
        dt = ' ' + dt[1:]
    if time.daylight and tt[-1]:
        zone = -time.altzone
    else:
        zone = -time.timezone
    return '"' + dt + " %+03d%02d" % divmod(zone//60, 60) + '"' 
Example 12
Project: pyblish-win   Author: pyblish   File: test_email.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        fp = openfile('PyBanner048.gif')
        try:
            data = fp.read()
        finally:
            fp.close()

        container = MIMEBase('multipart', 'mixed', boundary='BOUNDARY')
        image = MIMEImage(data, name='dingusfish.gif')
        image.add_header('content-disposition', 'attachment',
                         filename='dingusfish.gif')
        intro = MIMEText('''\
Hi there,

This is the dingus fish.
''')
        container.attach(intro)
        container.attach(image)
        container['From'] = 'Barry <[email protected]>'
        container['To'] = 'Dingus Lovers <[email protected]>'
        container['Subject'] = 'Here is your dingus fish'

        now = 987809702.54848599
        timetuple = time.localtime(now)
        if timetuple[-1] == 0:
            tzsecs = time.timezone
        else:
            tzsecs = time.altzone
        if tzsecs > 0:
            sign = '-'
        else:
            sign = '+'
        tzoffset = ' %s%04d' % (sign, tzsecs // 36)
        container['Date'] = time.strftime(
            '%a, %d %b %Y %H:%M:%S',
            time.localtime(now)) + tzoffset
        self._msg = container
        self._im = image
        self._txt = intro 
Example 13
Project: pyblish-win   Author: pyblish   File: test_email.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_formatdate_usegmt(self):
        now = time.time()
        self.assertEqual(
            Utils.formatdate(now, localtime=False),
            time.strftime('%a, %d %b %Y %H:%M:%S -0000', time.gmtime(now)))
        self.assertEqual(
            Utils.formatdate(now, localtime=False, usegmt=True),
            time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(now))) 
Example 14
Project: pyblish-win   Author: pyblish   File: test_email.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_parsedate_acceptable_to_time_functions(self):
        eq = self.assertEqual
        timetup = Utils.parsedate('5 Feb 2003 13:47:26 -0800')
        t = int(time.mktime(timetup))
        eq(time.localtime(t)[:6], timetup[:6])
        eq(int(time.strftime('%Y', timetup)), 2003)
        timetup = Utils.parsedate_tz('5 Feb 2003 13:47:26 -0800')
        t = int(time.mktime(timetup[:9]))
        eq(time.localtime(t)[:6], timetup[:6])
        eq(int(time.strftime('%Y', timetup[:9])), 2003) 
Example 15
Project: pyblish-win   Author: pyblish   File: test_email_renamed.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        fp = openfile('PyBanner048.gif')
        try:
            data = fp.read()
        finally:
            fp.close()

        container = MIMEBase('multipart', 'mixed', boundary='BOUNDARY')
        image = MIMEImage(data, name='dingusfish.gif')
        image.add_header('content-disposition', 'attachment',
                         filename='dingusfish.gif')
        intro = MIMEText('''\
Hi there,

This is the dingus fish.
''')
        container.attach(intro)
        container.attach(image)
        container['From'] = 'Barry <[email protected]>'
        container['To'] = 'Dingus Lovers <[email protected]>'
        container['Subject'] = 'Here is your dingus fish'

        now = 987809702.54848599
        timetuple = time.localtime(now)
        if timetuple[-1] == 0:
            tzsecs = time.timezone
        else:
            tzsecs = time.altzone
        if tzsecs > 0:
            sign = '-'
        else:
            sign = '+'
        tzoffset = ' %s%04d' % (sign, tzsecs // 36)
        container['Date'] = time.strftime(
            '%a, %d %b %Y %H:%M:%S',
            time.localtime(now)) + tzoffset
        self._msg = container
        self._im = image
        self._txt = intro 
Example 16
Project: pyblish-win   Author: pyblish   File: test_email_renamed.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_formatdate_localtime(self):
        now = time.time()
        self.assertEqual(
            utils.parsedate(utils.formatdate(now, localtime=True))[:6],
            time.localtime(now)[:6]) 
Example 17
Project: pyblish-win   Author: pyblish   File: test_email_renamed.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_formatdate_usegmt(self):
        now = time.time()
        self.assertEqual(
            utils.formatdate(now, localtime=False),
            time.strftime('%a, %d %b %Y %H:%M:%S -0000', time.gmtime(now)))
        self.assertEqual(
            utils.formatdate(now, localtime=False, usegmt=True),
            time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(now))) 
Example 18
Project: pyblish-win   Author: pyblish   File: dbapi2.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def DateFromTicks(ticks):
    return Date(*time.localtime(ticks)[:3]) 
Example 19
Project: pyblish-win   Author: pyblish   File: dbapi2.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def TimeFromTicks(ticks):
    return Time(*time.localtime(ticks)[3:6]) 
Example 20
Project: pyblish-win   Author: pyblish   File: dbapi2.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def TimestampFromTicks(ticks):
    return Timestamp(*time.localtime(ticks)[:6]) 
Example 21
Project: pyblish-win   Author: pyblish   File: BaseHTTPServer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
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 22
Project: pyblish-win   Author: pyblish   File: tarfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def list(self, verbose=True):
        """Print a table of contents to sys.stdout. If `verbose' is False, only
           the names of the members are printed. If it is True, an `ls -l'-like
           output is produced.
        """
        self._check()

        for tarinfo in self:
            if verbose:
                print filemode(tarinfo.mode),
                print "%s/%s" % (tarinfo.uname or tarinfo.uid,
                                 tarinfo.gname or tarinfo.gid),
                if tarinfo.ischr() or tarinfo.isblk():
                    print "%10s" % ("%d,%d" \
                                    % (tarinfo.devmajor, tarinfo.devminor)),
                else:
                    print "%10d" % tarinfo.size,
                print "%d-%02d-%02d %02d:%02d:%02d" \
                      % time.localtime(tarinfo.mtime)[:6],

            print tarinfo.name + ("/" if tarinfo.isdir() else ""),

            if verbose:
                if tarinfo.issym():
                    print "->", tarinfo.linkname,
                if tarinfo.islnk():
                    print "link to", tarinfo.linkname,
            print 
Example 23
Project: pyblish-win   Author: pyblish   File: test_zipimport.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testZipImporterMethodsInSubDirectory(self):
        packdir = TESTPACK + os.sep
        packdir2 = packdir + TESTPACK2 + os.sep
        files = {packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
                 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}

        z = ZipFile(TEMP_ZIP, "w")
        try:
            for name, (mtime, data) in files.items():
                zinfo = ZipInfo(name, time.localtime(mtime))
                zinfo.compress_type = self.compression
                z.writestr(zinfo, data)
            z.close()

            zi = zipimport.zipimporter(TEMP_ZIP + os.sep + packdir)
            self.assertEqual(zi.archive, TEMP_ZIP)
            self.assertEqual(zi.prefix, packdir)
            self.assertEqual(zi.is_package(TESTPACK2), True)
            mod = zi.load_module(TESTPACK2)
            self.assertEqual(zi.get_filename(TESTPACK2), mod.__file__)

            self.assertEqual(zi.is_package(TESTPACK2 + os.sep + '__init__'), False)
            self.assertEqual(zi.is_package(TESTPACK2 + os.sep + TESTMOD), False)

            mod_path = TESTPACK2 + os.sep + TESTMOD
            mod_name = module_path_to_dotted_name(mod_path)
            __import__(mod_name)
            mod = sys.modules[mod_name]
            self.assertEqual(zi.get_source(TESTPACK2), None)
            self.assertEqual(zi.get_source(mod_path), None)
            self.assertEqual(zi.get_filename(mod_path), mod.__file__)
            # To pass in the module name instead of the path, we must use the right importer
            loader = mod.__loader__
            self.assertEqual(loader.get_source(mod_name), None)
            self.assertEqual(loader.get_filename(mod_name), mod.__file__)
        finally:
            z.close()
            os.remove(TEMP_ZIP) 
Example 24
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        """Create time tuple based on current time."""
        self.time_tuple = time.localtime()
        self.LT_ins = _strptime.LocaleTime() 
Example 25
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_conversions(self):
        self.assertTrue(time.ctime(self.t)
                     == time.asctime(time.localtime(self.t)))
        self.assertTrue(long(time.mktime(time.localtime(self.t)))
                     == long(self.t)) 
Example 26
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_insane_timestamps(self):
        # It's possible that some platform maps time_t to double,
        # and that this test will fail there.  This test should
        # exempt such platforms (provided they return reasonable
        # results!).
        for func in time.ctime, time.gmtime, time.localtime:
            for unreasonable in -1e200, 1e200:
                self.assertRaises(ValueError, func, unreasonable) 
Example 27
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_localtime_without_arg(self):
        lt0 = time.localtime()
        lt1 = time.localtime(None)
        t0 = time.mktime(lt0)
        t1 = time.mktime(lt1)
        self.assertTrue(0 <= (t1-t0) < 0.2) 
Example 28
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_mktime(self):
        # Issue #1726687
        for t in (-2, -1, 0, 1):
            try:
                tt = time.localtime(t)
            except (OverflowError, ValueError):
                pass
            else:
                self.assertEqual(time.mktime(tt), t) 
Example 29
Project: pyblish-win   Author: pyblish   File: test_ssl.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def utc_offset(): #NOTE: ignore issues like #1647654
    # local time = utc time + utc offset
    if time.daylight and time.localtime().tm_isdst > 0:
        return -time.altzone  # seconds
    return -time.timezone 
Example 30
Project: pyblish-win   Author: pyblish   File: test_mailbox.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_from(self):
        # Get and set "From " line
        msg = mailbox.mboxMessage(_sample_message)
        self._check_from(msg)
        msg.set_from('foo bar')
        self.assertEqual(msg.get_from(), 'foo bar')
        msg.set_from('[email protected]', True)
        self._check_from(msg, '[email protected]')
        msg.set_from('[email protected]', time.localtime())
        self._check_from(msg, '[email protected]') 
Example 31
Project: pyblish-win   Author: pyblish   File: test_xmlrpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_time(self):
        d = 1181399930.036952
        t = xmlrpclib.DateTime(d)
        self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", time.localtime(d))) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_xmlrpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_time_struct(self):
        d = time.localtime(1181399930.036952)
        t = xmlrpclib.DateTime(d)
        self.assertEqual(str(t),  time.strftime("%Y%m%dT%H:%M:%S", d)) 
Example 33
Project: pyblish-win   Author: pyblish   File: rfc822.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def mktime_tz(data):
    """Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp."""
    if data[9] is None:
        # No zone info, so localtime is better assumption than GMT
        return time.mktime(data[:8] + (-1,))
    else:
        t = time.mktime(data[:8] + (0,))
        return t - data[9] - time.timezone 
Example 34
Project: pyblish-win   Author: pyblish   File: xmlrpclib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _strftime(value):
    if datetime:
        if isinstance(value, datetime.datetime):
            return "%04d%02d%02dT%02d:%02d:%02d" % (
                value.year, value.month, value.day,
                value.hour, value.minute, value.second)

    if not isinstance(value, (TupleType, time.struct_time)):
        if value == 0:
            value = time.time()
        value = time.localtime(value)

    return "%04d%02d%02dT%02d:%02d:%02d" % value[:6] 
Example 35
Project: oeffis-paper   Author: djaffry   File: display_driver.py    MIT License 5 votes vote down vote up
def _adjust_to_render_offset(transport_data):
        """
        Unfortunately the waveshare display takes about 60 seconds to display the information.
        Therefore the displayed time can be corrected by adding `renderOffset` to the server time minutes and
        subtracting `renderOffset` from the countdown time

        Input:
        Uses data from `config.json` with the following keys:
        display (json):                       display json with the following keys:
            renderOffset (number, optional):            offset in minutes used to add to displayed server time and subtract countdown

        :param transport_data
        :return: time adjusted transport_data
        """

        conf = get_config()
        if 'renderOffset' in conf['display']:
            corrected_seconds = time.mktime(transport_data['lastUpdate']) + conf['display']['renderOffset'] * 60
            transport_data['lastUpdate'] = time.localtime(corrected_seconds)

            offset_data = []
            for s in transport_data['stations']:
                for l in s['lines']:
                    # subtract `renderOffset` from countdown time
                    l['departures'] = [d - conf['display']['renderOffset']
                                       for d in l['departures'] if d - conf['display']['renderOffset'] >= 0]
                    if not l['departures']:
                        s['lines'].remove(l)  # removing lines with no departure time
                if s['lines']:
                    offset_data.append(s)  # removing stations with no lines
            return {'stations': offset_data, 'lastUpdate': transport_data['lastUpdate']}
        else:
            return transport_data 
Example 36
Project: face-attendance-machine   Author: matiji66   File: facerec_from_webcam_mult_thread.py    Apache License 2.0 5 votes vote down vote up
def process_face_records(name):
    """
    处理每一条识别的记录 ,并在一定时间之后将数据持久化到文件中
    此处会碰到全局并发,导致锁的问题
    :param name:
    :return:
    """
    return
    print('process_face_records start', time.time())

    global current_names, last_time
    # myprint("global current_names {}, last_time {}".format(current_names, last_time))

    # 判断是不是在识别的列表中,不在的话就进行问候
    if name not in current_names:
        print("ts ====", last_time, time.time())
        current_names.append(name)
        myprint("Hello {}, nice to meet you! ".format(name))
        # speaker.Speak("Hello {}, nice to meet you! ".format(name))

    # 在一定时间内,清空已经识别的人, 并进行
    if last_time < time.time() - TIME_DIFF:  # 每隔一段时间清空一下检测到的人
        last_time = time.time()
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        myprint(time_format + " update last_time and clear current_names.")
        with open(name_record, 'a') as f:
            if len(current_names) > 0:
                f.writelines("{}:{} \n".format(time_format, str(current_names)))
        print("======", current_names)
        current_names = []  # clear()
        current_names = [name]
        myprint('process_face_records end', time.time()) 
Example 37
Project: face-attendance-machine   Author: matiji66   File: facerec_from_webcam_faster.py    Apache License 2.0 5 votes vote down vote up
def process_face_records(name):
    """
    处理每一条识别的记录 ,并在一定时间之后将数据持久化到文件中
    :param name:
    :return:
    """
    print('process_face_records start', time.time())

    global current_names, last_time
    # myprint("global current_names {}, last_time {}".format(current_names, last_time))

    # 判断是不是在识别的列表中,不在的话就进行问候
    if name not in current_names:
        print("ts ====", last_time, time.time())
        current_names.append(name)
        myprint("Hello {}, nice to meet you! ".format(name))
        # speaker.Speak("Hello {}, nice to meet you! ".format(name))

    # 在一定时间内,清空已经识别的人, 并进行
    if last_time < time.time() - TIME_DIFF:  # 每隔一段时间清空一下检测到的人
        last_time = time.time()
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        myprint(time_format + " update last_time and clear current_names.")
        with open(name_record, 'a') as f:
            if len(current_names) > 0:
                f.writelines("{}:{} \n".format(time_format, str(current_names)))
        print("======", current_names)
        current_names = []  # clear()
        current_names = [name]
        myprint('process_face_records end', time.time()) 
Example 38
Project: zmirror   Author: aploium   File: _logtime.py    MIT License 5 votes vote down vote up
def logtime(is_print_date=False, timesep=':', datesep='-'):
    from time import time, localtime, strftime
    _localtime = localtime(time())
    _dateformat = '%Y' + datesep + '%m' + datesep + '%d'
    _timeformat = '%H' + timesep + '%M' + timesep + '%S'
    if is_print_date:
        return strftime(_dateformat + " " + _timeformat, _localtime)
    else:
        return strftime(_timeformat, _localtime) 
Example 39
Project: neural-fingerprinting   Author: StephanZheng   File: master.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _show_status_for_work(self, work):
    """Shows status for given work pieces.

    Args:
      work: instance of either AttackWorkPieces or DefenseWorkPieces
    """
    work_count = len(work.work)
    work_completed = {}
    work_completed_count = 0
    for v in itervalues(work.work):
      if v['is_completed']:
        work_completed_count += 1
        worker_id = v['claimed_worker_id']
        if worker_id not in work_completed:
          work_completed[worker_id] = {
              'completed_count': 0,
              'last_update': 0.0,
          }
        work_completed[worker_id]['completed_count'] += 1
        work_completed[worker_id]['last_update'] = max(
            work_completed[worker_id]['last_update'],
            v['claimed_worker_start_time'])
    print('Completed {0}/{1} work'.format(work_completed_count,
                                          work_count))
    for k in sorted(iterkeys(work_completed)):
      last_update_time = time.strftime(
          '%Y-%m-%d %H:%M:%S',
          time.localtime(work_completed[k]['last_update']))
      print('Worker {0}: completed {1}   last claimed work at {2}'.format(
          k, work_completed[k]['completed_count'], last_update_time)) 
Example 40
Project: Starx_Pixiv_Collector   Author: SuzukiHonoka   File: start.py    MIT License 5 votes vote down vote up
def print_with_tag(tag, data ,debug=0):
    data_print = data
    if type(data) == list:
        data_print = ''
        for per_data in data:
            if len(data_print) == 0:
                data_print += str(per_data)
            else:
                data_print += ' ' + str(per_data)
    if debug == 1:
        print('[' + time.asctime(time.localtime(time.time())) + '] ' + tag + ' =>', data_print)
    else:
        print(data_print) 
Example 41
Project: gluster-integration   Author: Tendrl   File: callback.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def georep_checkpoint_completed(self, event):
        georep_pair = "{0}:{1}:{2}--->{3}:{4}".format(
            event['message']["master_node"],
            event['message']["master_volume"],
            event['message']["brick_path"],
            event['message']["slave_host"],
            event['message']["slave_volume"]
        )
        context = "georep_checkpoint_completed|" + georep_pair
        cp_creation_time = time.localtime(
            float(event['message']['checkpoint_time'])
        )
        cp_creation_time = time.strftime("%d %b %Y %H:%M:%S", cp_creation_time)
        cp_completion_time = time.localtime(
            float(event['message']['checkpoint_completion_time'])
        )
        cp_completion_time = time.strftime(
            "%d %b %Y %H:%M:%S",
            cp_completion_time
        )

        message = "Georeplication checkpoint completed for pair {0}." \
                  " Check point creation time {1}." \
                  " Check point completion time {2}. in cluster {3}".format(
                      georep_pair,
                      cp_creation_time,
                      cp_completion_time,
                      self.cluster_short_name
                  )
        native_event = NS.gluster.objects.NativeEvents(
            context,
            message=message,
            severity="info",
            current_value="georep_checkpoint_completed",
            alert_notify=True
        )
        native_event.save() 
Example 42
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: tarfile.py    MIT License 5 votes vote down vote up
def list(self, verbose=True):
        """Print a table of contents to sys.stdout. If `verbose' is False, only
           the names of the members are printed. If it is True, an `ls -l'-like
           output is produced.
        """
        self._check()

        for tarinfo in self:
            if verbose:
                print(filemode(tarinfo.mode), end=' ')
                print("%s/%s" % (tarinfo.uname or tarinfo.uid,
                                 tarinfo.gname or tarinfo.gid), end=' ')
                if tarinfo.ischr() or tarinfo.isblk():
                    print("%10s" % ("%d,%d" \
                                    % (tarinfo.devmajor, tarinfo.devminor)), end=' ')
                else:
                    print("%10d" % tarinfo.size, end=' ')
                print("%d-%02d-%02d %02d:%02d:%02d" \
                      % time.localtime(tarinfo.mtime)[:6], end=' ')

            print(tarinfo.name + ("/" if tarinfo.isdir() else ""), end=' ')

            if verbose:
                if tarinfo.issym():
                    print("->", tarinfo.linkname, end=' ')
                if tarinfo.islnk():
                    print("link to", tarinfo.linkname, end=' ')
            print() 
Example 43
Project: push-button-get-candy   Author: channemann   File: PBGC.py    MIT License 5 votes vote down vote up
def getGlucoseDex():
	# Get most recent glucose from Dexcom Share
	# Code adapted from the Share to Nightscout bridge, via @bewest and @shanselman
	# https://github.com/bewest/share2nightscout-bridge
	# Login and get a Dexcom Share session ID
	# ... need to only do this once and then refresh the sessionID as necessary
	dexLoginURL = "https://share1.dexcom.com/ShareWebServices/Services/General/LoginPublisherAccountByName"
	dexLoginPayload = {
            "User-Agent": "Dexcom Share/3.0.2.11 CFNetwork/711.2.23 Darwin/14.0.0",
            "applicationId": "d89443d2-327c-4a6f-89e5-496bbb0317db",
            "accountName": dexUsername,
            "password": dexPassword,
        }
	dexLoginHeaders = {
	    'content-type': "application/json",
	    'accept': "application/json",
	    }
	dexLoginResponse = requests.post(dexLoginURL, json=dexLoginPayload, headers=dexLoginHeaders)
	sessionID = dexLoginResponse.json()
	# Use the session ID to retrieve the latest glucose record
	dexGlucoseURL = "https://share1.dexcom.com/ShareWebServices/Services/Publisher/ReadPublisherLatestGlucoseValues"
	dexGlucoseQueryString = {"sessionID":sessionID,"minutes":"1440","maxCount":"1"}
	dexGlucoseHeaders = {
	    'content-type': "application/json",
	    'accept': "application/json",
	    }
	dexGlucoseResponse = requests.post(dexGlucoseURL, headers=dexGlucoseHeaders, params=dexGlucoseQueryString)
	dexGlucoseResponseJSON = dexGlucoseResponse.json()
	dexGlucose = dexGlucoseResponseJSON[0]["Value"]
	dexGlucoseEpochString = dexGlucoseResponseJSON[0]["ST"]
	dexGlucoseEpoch = int(re.match('/Date\((\d+)\)/', dexGlucoseEpochString).group(1))/1e3
	dexGlucoseTimestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(dexGlucoseEpoch))
	print("Current Glucose (Share):      " + str(dexGlucose) + " " + glucoseUnit + " at " + time.strftime("%-I:%M:%S %p on %A, %B %d, %Y",time.localtime(dexGlucoseEpoch)))
	return dexGlucose 
Example 44
Project: pymapd-examples   Author: omnisci   File: OKR_oss_git.py    Apache License 2.0 5 votes vote down vote up
def get_views(r):
    # retrieve views information
    r_views = r.get_views_traffic()
    df = pd.DataFrame.from_dict(r_views)
    # iterate through individual view objects nested in the contents
    i = 0
    ts = pd.Series('ts', index=[i])
    cnt = pd.Series('cnt', index=[i])
    uni = pd.Series('uni', index=[i])
    repo = pd.Series('repo', index=[i])
    for view in df['views']: # this column contains a list of view objects
        i += 1
        repo[i] = r.name
        ts[i] = getattr(view, 'timestamp')
        ts[i] = ts[i]/1000000000
        ts[i] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(ts[i]))
        cnt[i] = getattr(view, 'count')
        uni[i] = getattr(view, 'uniques')

    # setup dataframe by concatenating the series together as columns
    list_of_series = [repo, ts, cnt, uni]
    # drop the column names before concatenating
    repo.drop([0], inplace = True)
    ts.drop([0], inplace = True)
    cnt.drop([0], inplace = True)
    uni.drop([0], inplace = True)
    df_views = pd.concat(list_of_series, axis=1, ignore_index=True)
    # rename the columns to useful labels
    columns = ['repo', 'view_timestamp', 'view_count', 'view_unique']
    print (df_views)
    df_views.columns = columns

    if df_views.empty:
        print ("no views")
    else:
        print (str(df_views['view_count'].sum()) + ' views for ' + r.name)
        return df_views 
Example 45
Project: spqrel_tools   Author: LCAS   File: naoqibag.py    MIT License 5 votes vote down vote up
def rhMonitorThread (memory_service, rate, output_file):
    print '%s Recording data at @%.2f Hz ...' %(time.strftime("%Y%m%d_%H%M%S", time.localtime()),rate)
    ts0 = time.time()
    tsl = []
    t = threading.currentThread()
    logheader(output_file,keys_list)
    while getattr(t, "do_run", True):
        try:
            values = memory_service.getListData(keys_list)
            if logdata(output_file,values):
                sys.stdout.write('.') # full log ok
            else:
                sys.stdout.write('-') # missing values
        except Exception as e:
            sys.stdout.write('X') # error
            print e
        dt = (int)(time.time() - ts0) / 60
        if (dt not in tsl):
            sys.stdout.write(str(dt))
            tsl.append(dt)
        sys.stdout.flush()
        time.sleep(1.0/rate)
    print "Exiting Thread Log"


# TTS callback
#Event: "ALTextToSpeech/CurrentSentence"
#callback(std::string eventName, std::string value, std::string subscriberIdentifier) 
Example 46
Project: flasky   Author: RoseOu   File: tarfile.py    MIT License 5 votes vote down vote up
def list(self, verbose=True):
        """Print a table of contents to sys.stdout. If `verbose' is False, only
           the names of the members are printed. If it is True, an `ls -l'-like
           output is produced.
        """
        self._check()

        for tarinfo in self:
            if verbose:
                print(filemode(tarinfo.mode), end=' ')
                print("%s/%s" % (tarinfo.uname or tarinfo.uid,
                                 tarinfo.gname or tarinfo.gid), end=' ')
                if tarinfo.ischr() or tarinfo.isblk():
                    print("%10s" % ("%d,%d" \
                                    % (tarinfo.devmajor, tarinfo.devminor)), end=' ')
                else:
                    print("%10d" % tarinfo.size, end=' ')
                print("%d-%02d-%02d %02d:%02d:%02d" \
                      % time.localtime(tarinfo.mtime)[:6], end=' ')

            print(tarinfo.name + ("/" if tarinfo.isdir() else ""), end=' ')

            if verbose:
                if tarinfo.issym():
                    print("->", tarinfo.linkname, end=' ')
                if tarinfo.islnk():
                    print("link to", tarinfo.linkname, end=' ')
            print() 
Example 47
Project: core   Author: lifemapper   File: server.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, package_metadata_filename, user_id, user_email=None):
        """Construct the command object

        Args:
            package_metadata_filename: The file location of the metadata file
                for the scenario package to be cataloged in the database
            user_id: The user id to use for this package
            user_email: The user email for this package
        """
        _LmDbServerCommand.__init__(self)
        
        # scen_package_meta may be full pathname or in ENV_DATA_PATH dir
        if not os.path.exists(package_metadata_filename):
            raise Exception(
                'Missing Scenario Package metadata file {}'.format(
                    package_metadata_filename))
        else:
            spBasename, _ = os.path.splitext(
                os.path.basename(package_metadata_filename)) 
            # file ends up in LOG_PATH
            secs = time.time()
            timestamp = "{}".format(
                time.strftime("%Y%m%d-%H%M", time.localtime(secs)))
            logname = '{}.{}.{}.{}'.format(
                self.scriptBasename, spBasename, user_id, timestamp)
            # Logfile is created by script in LOG_DIR
            logfilename = '{}{}'.format(logname, LMFormat.LOG.ext)
            
        # Required args
        self.args = '{} {}'.format(package_metadata_filename, user_id)
        # Optional arg, we also want for output 
        self.opt_args += ' --logname={}'.format(logname)
        # Optional arg, if user is not there, add with dummy email if not provided
        if user_email is not None:
            self.opt_args += ' --user_email={}'.format(user_email)
            
        self.outputs.append(logfilename)


# ............................................................................. 
Example 48
Project: core   Author: lifemapper   File: boom.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, config_filename, init_makeflow=False):
        """Construct the command object

        Args:
            config_filename: The file location of the ini file with parameters
                for a boom/gridset
        """
        _LmCommand.__init__(self)
        
        if not os.path.exists(config_filename):
            raise Exception(
                'Missing Boom configuration file {}'.format(config_filename))
        else:
            boomBasename, _ = os.path.splitext(
                os.path.basename(config_filename)) 
            # Logfile goes to LOG_DIR
            secs = time.time()
            timestamp = "{}".format(
                time.strftime("%Y%m%d-%H%M", time.localtime(secs)))
            logname = '{}.{}.{}'.format(
                self.scriptBasename, boomBasename, timestamp)
            logfilename = '{}{}'.format(logname, LMFormat.LOG.ext)
            
        # Script args
        self.args = config_filename
        self.args += ' --logname={}'.format(logname)
        if init_makeflow:
            self.args += ' --init_makeflow=True'
            
        self.outputs.append(logfilename) 
Example 49
Project: core   Author: lifemapper   File: boomer.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, configFname, successFname, log=None):      
        self.name = self.__class__.__name__.lower()
        # Logfile
        if log is None:
            secs = time.time()
            timestamp = "{}".format(time.strftime("%Y%m%d-%H%M", time.localtime(secs)))
            logname = '{}.{}'.format(self.name, timestamp)
            log = ScriptLogger(logname, level=logging.INFO)
        self.log = log
        
        self.configFname = configFname
        self._successFname = successFname
        
#         self.do_intersect = None
        self.do_pam_stats = None 
        self.do_mcpa = None 
        # Send Database connection
        self._scribe = BorgScribe(self.log)
        # iterator tool for species
        self.christopher = None

#         # Dictionary of {scenCode: (potatoChain, triagePotatoFile)}
#         self.potatoes = None

        # MFChain for lots of spuds 
        self.potatoBushel = None
        self.squidNames = None
        # Stop indicator
        self.keepWalken = False
        
        signal.signal(signal.SIGTERM, self._receiveSignal) # Stop signal

    # ............................. 
Example 50
Project: core   Author: lifemapper   File: boomer.py    GNU General Public License v3.0 5 votes vote down vote up
def restartWalken(self):
        if self.christopher.complete() and self.christopher.moreDataToProcess():
            # Rename old file
            oldfname = self.christopher.weaponOfChoice.occParser.dataFname
            ts = dt.localtime().tuple()
            timestamp = '{}{:02d}{:02d}-{:02d}{:02d}'.format(ts[0], ts[1], ts[2], ts[3], ts[4])
            newfname = oldfname + '.' + timestamp
            try:
                os.rename(oldfname, newfname)
            except Exception, e:
                self.log.error('Failed to rename {} to {}'.format(oldfname, newfname))
            # Restart with next file
            self.initializeMe()

    # ...............................................