当前位置: 首页>>代码示例>>Python>>正文


Python time.gmtime函数代码示例

本文整理汇总了Python中time.gmtime函数的典型用法代码示例。如果您正苦于以下问题:Python gmtime函数的具体用法?Python gmtime怎么用?Python gmtime使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了gmtime函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Navigation

    def Navigation(self, service, day_from):
      nav = "<P>"
      gmtime = time.gmtime( day_from + 24*3600 )
      
      #service menu
      for s in self.listServices():
        url = self.gmtime2url(s[0], gmtime)
        if s[0] == self.sel_service:
          nav = nav + "<B>%s</B>"%s[0]
        else:
          nav = nav + "<A href=\'%s%s%s\'>%s</A> "%(self.ip, self.scriptUrl, url, s[0])

      #date-day menu
      nav = nav + "</P>\n<P>"
      dayOfWeek = { 0:"Ne", 1:"Po", 2:"Ut", 3:"St", 4:"Ct", 5:"Pa", 6:"So" }

      for day in range(-2, 5):        
        gmtime = time.gmtime( day_from + day*24*3600 )
        date = time.strftime("%Y-%m-%d", gmtime)
        dayCode = int(time.strftime("%w", gmtime))
        date = date + "(" + dayOfWeek[dayCode] + ")"
        url = self.gmtime2url(service, gmtime)
        if day == 1:
          nav = nav + "<B>%s</B>"%date
        else:
          nav = nav + "<A href=\'%s\'>%s</A> "%(url, date)
      return nav + "</P>\n"
开发者ID:rohhy,项目名称:phspd,代码行数:27,代码来源:epgWeb.01.py

示例2: analyzePage

 def analyzePage(self):
     maxArchSize = str2size(self.get('maxarchivesize'))
     archCounter = int(self.get('counter','1'))
     oldthreads = self.Page.threads
     self.Page.threads = []
     T = time.mktime(time.gmtime())
     whys = []
     for t in oldthreads:
         if len(oldthreads) - self.archivedThreads <= int(self.get('minthreadsleft',5)):
             self.Page.threads.append(t)
             continue #Because there's too little threads left.
         #TODO: Make an option so that unstamped (unsigned) posts get archived.
         why = t.shouldBeArchived(self)
         if why:
             archive = self.get('archive')
             TStuple = time.gmtime(t.timestamp)
             vars = {
                     'counter' : archCounter,
                     'year' : TStuple[0],
                     'month' : TStuple[1],
                     'monthname' : int2month(TStuple[1]),
                     'monthnameshort' : int2month_short(TStuple[1]),
                     'week' : int(time.strftime('%W',TStuple)),
                     }
             archive = archive % vars
             if self.feedArchive(archive,t,maxArchSize,vars):
                 archCounter += 1
                 self.set('counter',str(archCounter))
             whys.append(why)
             self.archivedThreads += 1
         else:
             self.Page.threads.append(t)
     return set(whys)
开发者ID:pyropeter,项目名称:PyroBot-1G,代码行数:33,代码来源:archivebot.py

示例3: _set_expire

		def _set_expire(seconds=0):
			'''
			Creates a time object N seconds from now
			'''
			now = calendar.timegm(time.gmtime());
			then = now + seconds
			return time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime(then))
开发者ID:blindsightcorp,项目名称:rigor-webapp,代码行数:7,代码来源:__init__.py

示例4: handle_request

 def handle_request( self, trans, url, http_method=None, **kwd ):
     if 'Name' in kwd and not kwd[ 'Name' ]:
         # Hack: specially handle parameters named "Name" if no param_value is given
         # by providing a date / time string - guarantees uniqueness, if required.
         kwd[ 'Name' ] = time.strftime( "%a, %d %b %Y %H:%M:%S", time.gmtime() )
     if 'Comments' in kwd and not kwd[ 'Comments' ]:
         # Hack: specially handle parameters named "Comments" if no param_value is given
         # by providing a date / time string.
         kwd[ 'Comments' ] = time.strftime( "%a, %d %b %Y %H:%M:%S", time.gmtime() )
     socket.setdefaulttimeout( 600 )
     # The following calls to urllib2.urlopen() will use the above default timeout.
     try:
         if not http_method or http_method == 'get':
             page = urllib2.urlopen( url )
             response = page.read()
             page.close()
             return response
         elif http_method == 'post':
             page = urllib2.urlopen( url, urllib.urlencode( kwd ) )
             response = page.read()
             page.close()
             return response
         elif http_method == 'put':
             url += '/' + str( kwd.pop( 'id' ) ) + '?key=' + kwd.pop( 'key' )
             output = self.put( url, **kwd )
     except Exception, e:
         raise
         message = 'Problem sending request to the web application: %s.  URL: %s.  kwd: %s.  Http method: %s' % \
         ( str( e ), str( url ), str( kwd ), str( http_method )  )
         return self.handle_failure( trans, url, message )
开发者ID:HullUni-bioinformatics,项目名称:ReproPhyloGalaxy,代码行数:30,代码来源:common.py

示例5: main

def main():

    # zprava
    zprava = matrix([[20],[17],[2],[5],[6]])
    # klic
    klic = matrix([[18, 0,19,12,23],
                   [22,30,32,19,10],
                   [19,17, 2,32,32],
                   [11,24,20,22, 5],
                   [30, 0,19,26,22]])

    print "Brutal force started in",strftime("%H:%M:%S", gmtime())

    for a in range(26):
        print ""
        print a,
        for b in range(26):
            print ".",
            for c in range(26):
                for d in range(26):
                    for e in range(26):
                        matice = matrix([[a],[b],[c],[d],[e]])
                        nasobek = klic * matice
                        if ( (nasobek[0]%33==28) & (nasobek[1]%33==9) & (nasobek[2]%33==8) & (nasobek[3]%33==4) & (nasobek[4]%33==14)):
                            print matice

    print ""
    print "Brutal force ended in",strftime("%H:%M:%S", gmtime())                            
开发者ID:vojtasvoboda,项目名称:MathInPython,代码行数:28,代码来源:brutalForce.py

示例6: remind

def remind(phenny, input):
    m = r_command.match(input.bytes)
    if not m:
        return phenny.reply("Sorry, didn't understand the input.")
    length, scale, message = m.groups()

    length = float(length)
    factor = scaling.get(scale, 60)
    duration = length * factor

    if duration % 1:
        duration = int(duration) + 1
    else: duration = int(duration)

    t = int(time.time()) + duration
    reminder = (input.sender, input.nick, message)

    try: phenny.rdb[t].append(reminder)
    except KeyError: phenny.rdb[t] = [reminder]

    dump_database(phenny.rfn, phenny.rdb)

    if duration >= 60:
        w = ''
        if duration >= 3600 * 12:
            w += time.strftime(' on %d %b %Y', time.gmtime(t))
        w += time.strftime(' at %H:%MZ', time.gmtime(t))
        phenny.reply('Okay, will remind%s' % w)
    else: phenny.reply('Okay, will remind in %s secs' % duration)
开发者ID:thsnr,项目名称:phenny,代码行数:29,代码来源:remind.py

示例7: record

def record(session):
    starttime = time.time()
    call ("clear")
    print "Time-lapse recording started", time.strftime("%b %d %Y %I:%M:%S", time.localtime())
    print "CTRL-C to stop\n"
    print "Frames:\tTime Elapsed:\tLength @", session.fps, "FPS:"
    print "----------------------------------------"

    while True:
        routinestart = time.time()

        send_command(session)
        
        session.framecount += 1

        # This block uses the time module to format the elapsed time and final
        # video time displayed into nice xx:xx:xx format. time.gmtime(n) will
        # return the day, hour, minute, second, etc. calculated from the
        # beginning of time. So for instance, time.gmtime(5000) would return a
        # time object that would be equivalent to 5 seconds past the beginning
        # of time. time.strftime then formats that into 00:00:05. time.gmtime
        # does not provide actual milliseconds though, so we have to calculate
        # those seperately and tack them on to the end when assigning the length
        # variable. I'm sure this isn't the most elegant solution, so
        # suggestions are welcome.
        elapsed = time.strftime("%H:%M:%S", time.gmtime(time.time()-starttime))
        vidsecs = float(session.framecount)/session.fps
        vidmsecs = str("%02d" % ((vidsecs - int(vidsecs)) * 100))
        length = time.strftime("%H:%M:%S.", time.gmtime(vidsecs)) + vidmsecs

        stdout.write("\r%d\t%s\t%s" % (session.framecount, elapsed, length))
        stdout.flush()
        time.sleep(session.interval - (time.time() - routinestart))
开发者ID:j0npau1,项目名称:pimento,代码行数:33,代码来源:pimento.py

示例8: lambda_handler

def lambda_handler(event, context):
    print "=== Start parsing EBS backup script. ==="
    ec2 = boto3.client('ec2')
    response = ec2.describe_instances()
    namesuffix = time.strftime('-%Y-%m-%d-%H-%M')
    data = None

    # Get current day + hour (using GMT)
    hh = int(time.strftime("%H", time.gmtime()))
    day = time.strftime("%a", time.gmtime()).lower()

    exclude_list = config['exclude']

    # Loop Volumes.
    try:
        for r in response['Reservations']:
            for ins in r['Instances']:
                for t in ins['Tags']:
                    if t['Key'] == 'Name':
                        for namestr in config['exclude_name']:
                            if namestr in t['Value']:
                                print 'Excluding Instance with ID ' + ins['InstanceId']
                                exclude_list.append(ins['InstanceId'])
                    if (ins['InstanceId'] not in exclude_list) and (not any('ignore' in t['Key'] for t in ins['Tags'])):
                        for tag in ins['Tags']:
                            if tag['Key'] == config['tag']:
                                data = tag['Value']

                        if data is None and config['auto-create-tag'] == 'true':
                            print "Instance %s doesn't contains the tag and auto create is enabled." % ins['InstanceId']
                            create_backup_tag(ins, ec2)
                            data = config['default']
                        schedule = json.loads(data)
                        data = None

                        if hh == schedule['time'][day] and not ins['State']['Name'] == 'terminated':
                            print "Getting the list of EBS volumes attached to \"%s\" ..." % ins['InstanceId']
                            volumes = ins['BlockDeviceMappings']
                            for vol in volumes:
                                vid = vol['Ebs']['VolumeId']
                                print "Creating snapshot of volume \"%s\" ..." % (vid)
                                snap_res = ec2.create_snapshot(VolumeId=vid, Description=vid + namesuffix)
                                if snap_res['State'] == 'error':
                                    notify_topic('Failed to create snapshot for volume with ID %s.\nCheck Cloudwatch \
                                                 logs for more details.' % vid)
                                    sys.exit(1)
                                elif maintain_retention(ec2, vid, schedule['retention']) != 0:
                                    print "Failed to maintain the retention period appropriately."
                    else:
                        print "Instance %s is successfully ignored." % ins['InstanceId']
    except botocore.exceptions.ClientError as e:
        print 'Recieved Boto client error %s' % e
    except KeyError as k:
        if config['auto-create-tag'] == 'true':
            print "Inside KeyError %s" % k
            create_backup_tag(ins, ec2)
    except ValueError:
        # invalid json
        print 'Invalid value for tag \"backup\" on instance \"%s\", please check!' % (ins['InstanceId'])
    print "=== Finished parsing EBS backup script. ==="
开发者ID:chaitu6022,项目名称:aws-lambda-functions,代码行数:60,代码来源:ebs-scheduled-backup.py

示例9: run

 def run(self, objfile):
     self.key = "PETimestamp"
     self.score = 0
     
     if objfile.get_type() == 'PE32' or objfile.get_type() == 'MS-DOS':
         timeStamp = None
         
         try:
             pe = PE(data=objfile.file_data)
             peTimeDateStamp = pe.FILE_HEADER.TimeDateStamp
             timeStamp = '0x%-8X' % (peTimeDateStamp)
             try:
                 timeStamp += ' [%s UTC]' % time.asctime(time.gmtime(peTimeDateStamp))
                 peYear = time.gmtime(peTimeDateStamp)[0]
                 thisYear = time.gmtime(time.time())[0]
                 if peYear < 2000 or peYear > thisYear:
                     timeStamp += " [SUSPICIOUS]"
                     self.score = 10
             except:
                 timeStamp += ' [SUSPICIOUS]'
                 self.score = 10
             
             return timeStamp
         except PEFormatError, e:
             log.warn("Error - No Portable Executable or MS-DOS: %s" % e)        
开发者ID:foreni-packages,项目名称:ragpicker_v0.05.2,代码行数:25,代码来源:peTimestamp.py

示例10: pbot

def pbot(message, channel=''):
    if channel: 
        msg = '[%s %s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), channel, 'BOT', message)
    else: 
        msg = '[%s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), 'BOT', message)

    print msg
开发者ID:starthal,项目名称:twitchplays-cookieclicker,代码行数:7,代码来源:misc.py

示例11: for_key

 def for_key(self, key, params=None, bucket_name=None):
     if params:
         self.update(params)
     if key.path:
         t = os.path.split(key.path)
         self['OriginalLocation'] = t[0]
         self['OriginalFileName'] = t[1]
         mime_type = mimetypes.guess_type(t[1])[0]
         if mime_type is None:
             mime_type = 'application/octet-stream'
         self['Content-Type'] = mime_type
         s = os.stat(key.path)
         t = time.gmtime(s[7])
         self['FileAccessedDate'] = get_ts(t)
         t = time.gmtime(s[8])
         self['FileModifiedDate'] = get_ts(t)
         t = time.gmtime(s[9])
         self['FileCreateDate'] = get_ts(t)
     else:
         self['OriginalFileName'] = key.name
         self['OriginalLocation'] = key.bucket.name
         self['ContentType'] = key.content_type
     self['Host'] = gethostname()
     if bucket_name:
         self['Bucket'] = bucket_name
     else:
         self['Bucket'] = key.bucket.name
     self['InputKey'] = key.name
     self['Size'] = key.size
开发者ID:10sr,项目名称:hue,代码行数:29,代码来源:message.py

示例12: handleStaticResource

def handleStaticResource(req):
    if req.path == "static-resource/":
        raise request.Forbidden("Directory listing disabled!")
    resources_path = os.path.join(
        configuration.paths.INSTALL_DIR, "resources")
    resource_path = os.path.abspath(os.path.join(
        resources_path, req.path.split("/", 1)[1]))
    if not resource_path.startswith(resources_path + "/"):
        raise request.Forbidden()
    if not os.path.isfile(resource_path):
        raise request.NotFound()
    last_modified = htmlutils.mtime(resource_path)
    HTTP_DATE = "%a, %d %b %Y %H:%M:%S GMT"
    if_modified_since = req.getRequestHeader("If-Modified-Since")
    if if_modified_since:
        try:
            if_modified_since = time.strptime(if_modified_since, HTTP_DATE)
        except ValueError:
            pass
        else:
            if last_modified <= calendar.timegm(if_modified_since):
                raise request.NotModified()
    req.addResponseHeader("Last-Modified", time.strftime(HTTP_DATE, time.gmtime(last_modified)))
    if req.query and req.query == htmlutils.base36(last_modified):
        req.addResponseHeader("Expires", time.strftime(HTTP_DATE, time.gmtime(time.time() + 2592000)))
        req.addResponseHeader("Cache-Control", "max-age=2592000")
    setContentTypeFromPath(req)
    req.start()
    with open(resource_path, "r") as resource_file:
        return [resource_file.read()]
开发者ID:jensl,项目名称:critic,代码行数:30,代码来源:critic.py

示例13: __call__

 def __call__(self, parser, namespace, values, option_string=None):
     """
     Each action should call this logic.
     """
         
     dis_dict = {'--add': '+',
                 '--remove': '-',
                 '-a': '+',
                 '-rm': '-',
                 '--reset': '*'}
     #debug
     #print '%r %r %r' % (namespace, values, option_string)
     if option_string == '--reset':
         print 'Base reset to: ', values
         Log.history.append(('*' + str(values),
                            time.strftime(STATIC_T, time.gmtime())))
         Log.save_log()
     elif option_string == '--clear':
         Log.history = []
         Log.save_log()
         os.remove(STATIC_P)
         sys.exit('Clear all data...OK')
     else:
         try:
             Log.history.append((dis_dict[option_string] + str(values),
                                 time.strftime(STATIC_T, time.gmtime())))
         except KeyError:
             pass
         else:
             Log.save_log()
         Log.print_log()
开发者ID:jacob-carrier,项目名称:code,代码行数:31,代码来源:recipe-577280.py

示例14: post

 def post(self, *args, **kwargs):
     art = ArticleObject()
     art.title = self.get_argument("title")
     art.slug_name = self.get_argument("uri")
     art.content = self.get_argument("content")
     art.morecontent = self.get_argument("morecontent")
     try:
         q = strptime(self.get_argument("pub_date"), "%m/%d/%Y")
         art.pub_date = strftime("%Y-%m-%d", q)
         art.rfc822_date = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
     except:
         q = strptime(self.get_argument("pub_date"), "%Y-%m-%d")
         art.pub_date = self.get_argument("pub_date")
         art.rfc822_date = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
     art.author = self.get_argument("name")
     art.category = self.get_argument("category")
     art.tags = self.get_argument("tags")
     art.posted = False
     art.twit = False
     art.absolute_url = 'http://ukrgadget/' + \
         self.get_argument("category") + '/' + self.get_argument("uri")
     art.short_url = 'http://ukrgadget.com/go/' + \
         str(self.application.database.find().count() + 1)
     ident = self.application.database.insert(art.dict())
     self.redirect('/admin/edit/' + str(ident), permanent=False, status=302)
开发者ID:skl1f,项目名称:ukrgadget,代码行数:25,代码来源:server.py

示例15: enumerate_recent_revisions

    def enumerate_recent_revisions(self, start_day, end_day):
        self.logger.info('enumerating revisions from %s through %s' %
                (ccm.util.to_date(start_day), ccm.util.to_date(end_day)))
        start_str = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(start_day))
        end_str = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(end_day))
        out = subprocess.check_output(['git', 'log',
                                       '--since', start_str, '--until', end_str,
                                       '--format=format:%H %ct %aE', '--shortstat'],
            cwd=self.local_path)
        out = out.split('\n')

        hash_re = re.compile(r'^([a-z0-9]{40}) (\d+) ([^ ]+)')
        shortstat_re = re.compile(r'\s*\d+ files? changed(, (\d+) insertions?...)?(, (\d+) deletions?...)?')
        rv = []
        while out:
            line = out.pop(0)
            mo = hash_re.match(line)
            if mo:
                rv.append(Rev())
                rv[-1].revision, rv[-1].when, rv[-1].author = mo.groups()
            mo = shortstat_re.match(line)
            if mo:
                if mo.group(2):
                    rv[-1].added = int(mo.group(2))
                if mo.group(4):
                    rv[-1].removed = int(mo.group(4))
        return rv
开发者ID:djmitche,项目名称:code-change-monitor,代码行数:27,代码来源:vcs.py


注:本文中的time.gmtime函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。