Python time.localtime() Examples

The following are 30 code examples for showing how to use time.localtime(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module time , or try the search function .

Example 1
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: GameOfLife.py    License: MIT License 6 votes vote down vote up
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 2
Project: InsightAgent   Author: insightfinder   File: getmetrics_nfdump.py    License: Apache License 2.0 6 votes vote down vote up
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 3
Project: SublimeKSP   Author: nojanath   File: cpp.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 4
Project: SublimeKSP   Author: nojanath   File: preprocessor_plugins.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 5
Project: gw2pvo   Author: markruys   File: pvo_api.py    License: MIT License 6 votes vote down vote up
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 6
Project: BatteryMonitor   Author: simat   File: summary.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 7
Project: BatteryMonitor   Author: simat   File: alarms.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 8
Project: BatteryMonitor   Author: simat   File: getbms.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 9
Project: raspberrypi-examples   Author: timwaizenegger   File: tm1637.py    License: MIT License 6 votes vote down vote up
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 10
Project: password_pwncheck   Author: CboeSecurity   File: password-pwncheck.py    License: MIT License 6 votes vote down vote up
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 11
Project: jawfish   Author: war-and-code   File: __init__.py    License: MIT License 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(self.default_time_format, ct)
            s = self.default_msec_format % (t, record.msecs)
        return s 
Example 12
Project: Vxscan   Author: al0ne   File: sqldb.py    License: Apache License 2.0 6 votes vote down vote up
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 13
Project: Vxscan   Author: al0ne   File: sqldb.py    License: Apache License 2.0 6 votes vote down vote up
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 14
Project: risk-slim   Author: ustunb   File: helper_functions.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 15
Project: verge3d-blender-addon   Author: Soft8Soft   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 16
Project: verge3d-blender-addon   Author: Soft8Soft   File: datetime.py    License: GNU General Public License v3.0 6 votes vote down vote up
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 17
Project: 21tb_robot   Author: iloghyr   File: study_robot.py    License: 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 18
Project: controllable-text-attribute-transfer   Author: Nrgeup   File: main.py    License: Apache License 2.0 5 votes vote down vote up
def add_log(ss):
    now_time = time.strftime("[%Y-%m-%d %H:%M:%S]: ", time.localtime())
    print(now_time + ss)
    with open(args.log_file, 'a') as f:
        f.write(now_time + str(ss) + '\n')
    return 
Example 19
Project: controllable-text-attribute-transfer   Author: Nrgeup   File: main.py    License: Apache License 2.0 5 votes vote down vote up
def preparation():
    # set model save path
    if args.if_load_from_checkpoint:
        timestamp = args.checkpoint_name
    else:
        timestamp = str(int(time.time()))
        print("create new model save path: %s" % timestamp)
    args.current_save_path = 'save/%s/' % timestamp
    args.log_file = args.current_save_path + time.strftime("log_%Y_%m_%d_%H_%M_%S.txt", time.localtime())
    args.output_file = args.current_save_path + time.strftime("output_%Y_%m_%d_%H_%M_%S.txt", time.localtime())
    print("create log file at path: %s" % args.log_file)

    if os.path.exists(args.current_save_path):
        add_log("Load checkpoint model from Path: %s" % args.current_save_path)
    else:
        os.makedirs(args.current_save_path)
        add_log("Path: %s is created" % args.current_save_path)

    # set task type
    if args.task == 'yelp':
        args.data_path = '../../data/yelp/processed_files/'
    elif args.task == 'amazon':
        args.data_path = '../../data/amazon/processed_files/'
    elif args.task == 'imagecaption':
        pass
    else:
        raise TypeError('Wrong task type!')

    # prepare data
    args.id_to_word, args.vocab_size, \
    args.train_file_list, args.train_label_list = prepare_data(
        data_path=args.data_path, max_num=args.word_dict_max_num, task_type=args.task
    )
    return 
Example 20
Project: controllable-text-attribute-transfer   Author: Nrgeup   File: main.py    License: Apache License 2.0 5 votes vote down vote up
def add_log(ss):
    now_time = time.strftime("[%Y-%m-%d %H:%M:%S]: ", time.localtime())
    print(now_time + ss)
    with open(args.log_file, 'a') as f:
        f.write(now_time + str(ss) + '\n')
    return 
Example 21
Project: controllable-text-attribute-transfer   Author: Nrgeup   File: main.py    License: Apache License 2.0 5 votes vote down vote up
def preparation():
    # set model save path
    if args.if_load_from_checkpoint:
        timestamp = args.checkpoint_name
    else:
        timestamp = str(int(time.time()))
        print("create new model save path: %s" % timestamp)
    args.current_save_path = 'save/%s/' % timestamp
    args.log_file = args.current_save_path + time.strftime("log_%Y_%m_%d_%H_%M_%S.txt", time.localtime())
    args.output_file = args.current_save_path + time.strftime("output_%Y_%m_%d_%H_%M_%S.txt", time.localtime())
    print("create log file at path: %s" % args.log_file)

    if os.path.exists(args.current_save_path):
        add_log("Load checkpoint model from Path: %s" % args.current_save_path)
    else:
        os.makedirs(args.current_save_path)
        add_log("Path: %s is created" % args.current_save_path)

    # set task type
    if args.task == 'yelp':
        args.data_path = '../../data/yelp/processed_files/'
    elif args.task == 'amazon':
        args.data_path = '../../data/amazon/processed_files/'
    elif args.task == 'imagecaption':
        args.data_path = '../../data/imagecaption/processed_files/'
    else:
        raise TypeError('Wrong task type!')

    # prepare data
    args.id_to_word, args.vocab_size, \
    args.train_file_list, args.train_label_list = prepare_data(
        data_path=args.data_path, max_num=args.word_dict_max_num, task_type=args.task
    )
    return 
Example 22
Project: controllable-text-attribute-transfer   Author: Nrgeup   File: main.py    License: Apache License 2.0 5 votes vote down vote up
def add_log(ss):
    now_time = time.strftime("[%Y-%m-%d %H:%M:%S]: ", time.localtime())
    print(now_time + ss)
    with open(args.log_file, 'a') as f:
        f.write(now_time + str(ss) + '\n')
    return 
Example 23
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: hexclock.py    License: MIT License 5 votes vote down vote up
def step(self, amt=1):
        t = time.localtime()
        hex = "#{0:0>2}{1:0>2}{2:0>2}".format(t.tm_hour, t.tm_min, t.tm_sec)
        c = COLORS[hex]
        self.layout.fill(c)

        self._step = 0 
Example 24
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: RGBClock.py    License: MIT License 5 votes vote down vote up
def step(self, amt=1):
        t = time.localtime()

        r, g, b = self.palette(t.tm_hour * (256 // 24))
        self.layout.fillRGB(r, g, b, self._hStart, self._hEnd)

        r, g, b = self.palette(t.tm_min * (256 // 60))
        self.layout.fillRGB(r, g, b, self._mStart, self._mEnd)

        r, g, b = self.palette(t.tm_sec * (256 // 60))
        self.layout.fillRGB(r, g, b, self._sStart, self._sEnd) 
Example 25
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: TallClock.py    License: MIT License 5 votes vote down vote up
def step(self, amt):
        self.layout.setTexture([[self.palette(
            y * 255 / self.height + self._step * 2)] * self.width for y in range(self.height)])
        self.layout.all_off()
        t = time.localtime()
        hrs = str(t.tm_hour).zfill(2)
        mins = str(t.tm_min).zfill(2)
        sec = str(t.tm_sec).zfill(2)
        self.layout.drawText(hrs, x=2, y=2, font_scale=2)
        self.layout.drawText(mins, x=2, y=18, font_scale=2)
        self.layout.drawText(sec, x=2, y=34, font_scale=2)

        self._step += amt
        self.layout.setTexture(tex=None) 
Example 26
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: GradientClock.py    License: MIT License 5 votes vote down vote up
def step(self, amt=1):
        self.layout.all_off()
        t = time.localtime()
        hrs = t.tm_hour % 12
        mins = t.tm_min
        sec = t.tm_sec

        h_hrs = hrs * (256 // 12)
        h_min = mins * (256 // 60)
        h_sec = sec * (256 // 60)

        grad = []

        grad += hue_gradient(h_hrs, h_min, self.half)
        if self.odd:
            grad += [h_min]
        grad += hue_gradient(h_min, h_sec, self.half)

        log.debug('{}:{}:{}'.format(hrs, mins, sec))

        for x in range(self.cdim):
            self.layout.drawLine(x, 0, x, self.height - 1,
                                 self.palette(grad[x])) 
Example 27
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: OneKClock.py    License: MIT License 5 votes vote down vote up
def step(self, amt):
        self.layout.setTexture([[self.palette(
            y * 255 / self.height + self._step * 2)] * self.width for y in range(self.height)])
        self.layout.all_off()
        t = time.localtime()
        hrs = str(t.tm_hour).zfill(2)
        mins = str(t.tm_min).zfill(2)
        secs = str(t.tm_sec).zfill(2)
        self.layout.drawText(hrs, x=0, y=0, font_scale=2)
        self.layout.drawText(mins, x=0, y=18, font_scale=2)
        self.layout.drawText(secs[0], x=24, y=8)
        self.layout.drawText(secs[1], x=24, y=17)

        self._step += amt
        self.layout.setTexture(tex=None) 
Example 28
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: AnalogClock.py    License: MIT License 5 votes vote down vote up
def step(self, amt=1):
        self.layout.all_off()
        t = time.localtime()
        hrs = t.tm_hour % 12
        mins = t.tm_min
        sec = t.tm_sec

        p_hrs = pointOnCircle(self._centerX, self._centerY, int(self.hand_length * 0.7), hrs * 30)
        p_min = pointOnCircle(self._centerX, self._centerY, self.hand_length, mins * 6)
        p_sec = pointOnCircle(self._centerX, self._centerY, self.hand_length, sec * 6)

        c_hrs = self.palette(hrs * (256 // 12))
        c_min = self.palette(mins * (256 // 60))
        c_sec = self.palette(sec * (256 // 60))

        self.layout.drawLine(self._centerX, self._centerY, p_hrs[0], p_hrs[1], c_hrs, aa=self.aa)
        self.layout.drawLine(self._centerX, self._centerY, p_min[0], p_min[1], c_min, aa=self.aa)
        self.layout.drawLine(self._centerX, self._centerY, p_sec[0], p_sec[1], c_sec, aa=self.aa) 
Example 29
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: arc_clock.py    License: MIT License 5 votes vote down vote up
def step(self, amt=1):
        self.layout.all_off()
        t = time.localtime()
        for h in self.hands:
            segs = h['segments']
            end = (360 / segs) * (getattr(t, h['key']) % segs)
            if end:
                for i in h['rings']:
                    self.layout.fillRing(
                        i, h['color'], startAngle=0, endAngle=end) 
Example 30
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: ring_clock.py    License: MIT License 5 votes vote down vote up
def step(self, amt=1):
        self.layout.all_off()
        t = time.localtime()
        for h in self.hands:
            segs = h['segments']
            point = (360 / segs) * (getattr(t, h['key']) % segs)
            self.layout.set(h['ring'], point, h['color'])
            if h['tail'] > 0:
                for i in range(h['tail']):
                    scaled = color_scale(h['color'], 255 - ((256 // h['tail']) * i))
                    self.layout.set(h['ring'], point + i, scaled)
                    self.layout.set(h['ring'], point - i, scaled)