python类gmtime()的实例源码

test_13_SDDS.py 文件源码 项目:core-framework 作者: RedhawkSDR 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_init(self):
        tod=time.time()
        sdds_time = Time()
        sdds_time.setFromTime(tod)

        # test current time of day
        self.assertEqual( sdds_time.seconds(), tod )

        # test current time of day struct
        self.assertEqual( sdds_time.gmtime(), time.gmtime(tod))

        # set parts
        sdds_time.set( 1234, 5678 )
        self.assertEqual( sdds_time.picoTicks(), 1234 )
        self.assertEqual( sdds_time.picoTicksFractional(), 5678 )

        # set partial
        sdds_time.setFromPartial( 4, .001 )
        self.assertEqual( sdds_time.picoTicks(), (4000000000*4) + long(4000000000*0.001) )
        self.assertEqual( sdds_time.picoTicksFractional(), 0 )
rfc822.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def formatdate(timeval=None):
    """Returns time format preferred for Internet standards.

    Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123

    According to RFC 1123, day and month names must always be in
    English.  If not for that, this code could use strftime().  It
    can't because strftime() honors the locale and could generated
    non-English names.
    """
    if timeval is None:
        timeval = time.time()
    timeval = time.gmtime(timeval)
    return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (
            ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")[timeval[6]],
            timeval[2],
            ("Jan", "Feb", "Mar", "Apr", "May", "Jun",
             "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")[timeval[1]-1],
                                timeval[0], timeval[3], timeval[4], timeval[5])


# When used as script, run a small test program.
# The first command line argument must be a filename containing one
# message in RFC-822 format.
tarfile.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def __init__(self, file, mode="r", compression=TAR_PLAIN):
        from warnings import warnpy3k
        warnpy3k("the TarFileCompat class has been removed in Python 3.0",
                stacklevel=2)
        if compression == TAR_PLAIN:
            self.tarfile = TarFile.taropen(file, mode)
        elif compression == TAR_GZIPPED:
            self.tarfile = TarFile.gzopen(file, mode)
        else:
            raise ValueError("unknown compression constant")
        if mode[0:1] == "r":
            members = self.tarfile.getmembers()
            for m in members:
                m.filename = m.name
                m.file_size = m.size
                m.date_time = time.gmtime(m.mtime)[:6]
__init__.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 25 收藏 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
Cookie.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _getdate(future=0, weekdayname=_weekdayname, monthname=_monthname):
    from time import gmtime, time
    now = time()
    year, month, day, hh, mm, ss, wd, y, z = gmtime(now + future)
    return "%s, %02d-%3s-%4d %02d:%02d:%02d GMT" % \
           (weekdayname[wd], day, monthname[month], year, hh, mm, ss)


#
# A class to hold ONE key,value pair.
# In a cookie, each such pair may have several attributes.
#       so this class is used to keep the attributes associated
#       with the appropriate key,value pair.
# This class also includes a coded_value attribute, which
#       is used to hold the network representation of the
#       value.  This is most useful when Python objects are
#       pickled for network transit.
#
mailbox.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _install_message(self, message):
        """Format a message and blindly write to self._file."""
        from_line = None
        if isinstance(message, str) and message.startswith('From '):
            newline = message.find('\n')
            if newline != -1:
                from_line = message[:newline]
                message = message[newline + 1:]
            else:
                from_line = message
                message = ''
        elif isinstance(message, _mboxMMDFMessage):
            from_line = 'From ' + message.get_from()
        elif isinstance(message, email.message.Message):
            from_line = message.get_unixfrom()  # May be None.
        if from_line is None:
            from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime())
        start = self._file.tell()
        self._file.write(from_line + os.linesep)
        self._dump_message(message, self._file, self._mangle_from_)
        stop = self._file.tell()
        return (start, stop)
main.py 文件源码 项目:sea-lion-counter 作者: rdinse 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def main(_):
  config = flags.FLAGS.__flags.copy()
  config.update(json.loads(config['config']))
  del config['config']
  if config['results_dir'] == '':
    del config['results_dir']

  if config['task'] == 'search':
    # Hyperparameter search cannot be continued, so a new results dir is created.
    config['results_dir'] = os.path.join(results_dir, 'hs', config['model_name'] \
            + time.strftime('_%Y-%m-%d_%H-%M-%S', time.gmtime()))
    hb = Hyperband(config)
    results = hb.run()
  else:
    model = make_model(config)
    if config['task'] == 'train':
      model.train()
    elif config['task'] == 'test':
      model.test()
    else:
      print('Invalid argument: --task=%s. ' \
            + 'It should be either of {train, test, search}.' % config['task'])
timeTools.py 文件源码 项目:otRebuilder 作者: Pal3love 项目源码 文件源码 阅读 32 收藏 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
__init__.py 文件源码 项目:oscars2016 作者: 0x0ece 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def request(self, method, request_uri, headers, content):
        """Modify the request headers"""
        keys = _get_end2end_headers(headers)
        keylist = "".join(["%s " % k for k in keys])
        headers_val = "".join([headers[k] for k in keys])
        created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())
        cnonce = _cnonce()
        request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val)
        request_digest  = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower()
        headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % (
                self.credentials[0],
                self.challenge['realm'],
                self.challenge['snonce'],
                cnonce,
                request_uri,
                created,
                request_digest,
                keylist)
extrinsics.py 文件源码 项目:cfpp 作者: dcoker 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def strftime(config, context, arg, now=time.gmtime()):
    """
    strftime returns the current time (in UTC) converted to the format
    specified by the first argument. The format is specified using
    Python's time.strftime format (
    https://docs.python.org/2/library/time.html#time.strftime).

    Example:
        {"CFPP::Strftime": "%Y%m%d_%H%M%S"}  ==>  20060102_220405

    Note: use special care when using this function with CloudFormation's
    "update" functionality. The output of this function will change each
    time cfpp is run.
    """
    _raise_unless_string(context, arg)
    return time.strftime(arg, now)
mpepool.py 文件源码 项目:PyExPool 作者: eXascaleInfolab 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def timeheader(timestamp=time.gmtime()):
    """Timestamp header string

    timestamp  - timestamp

    return  - timetamp string for the file header
    """
    assert isinstance(timestamp, time.struct_time), 'Unexpected type of timestamp'
    # ATTENTION: MPE pool timestamp [prefix] intentionally differs a bit from the
    # benchmark timestamp to easily find/filter each of them
    return time.strftime('# ----- %Y-%m-%d %H:%M:%S ' + '-'*30, timestamp)


# Limit the amount of memory consumption by worker processes.
# NOTE:
#  - requires import of psutils
#  - automatically reduced to the RAM size if the specidied limit is larger
wmo_file.py 文件源码 项目:Blender-WMO-import-export-scripts 作者: WowDevTools 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def save_liquids(self):
        start_time = time.time()

        for liquid_obj in self.bl_scene_objects.liquids:
            print("\nSaving liquid: <<{}>>".format(liquid_obj.name))

            if not liquid_obj.WowLiquid.WMOGroup:
                print("WARNING: Failed saving liquid: <<{}>>".format(liquid_obj.name))
                continue
            group_obj = bpy.context.scene.objects[liquid_obj.WowLiquid.WMOGroup]

            group_index = group_obj.WowWMOGroup.GroupID
            group = self.groups[group_index]

            group.save_liquid(liquid_obj)

            print("Done saving liquid: <<{}>>".format(liquid_obj.name))

        print("\nDone saving liquids. "
              "\nTotal saving time: ", time.strftime("%M minutes %S seconds", time.gmtime(time.time() - start_time)))
wow.py 文件源码 项目:Blender-WMO-import-export-scripts 作者: WowDevTools 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def open_game_resources(wow_path):
        """Open game resources and store links to them in memory"""

        print("\nProcessing available game resources of client: " + wow_path)
        start_time = time.time()

        if WoWFileData.is_wow_path_valid(wow_path):
            data_packages = WoWFileData.list_game_data_paths(os.path.join(wow_path, "Data\\"))
            resource_map = []

            for package in data_packages:
                if os.path.isfile(package):
                    resource_map.append((mpyq.MPQArchive(package, listfile=False), True))
                    print("\nLoaded MPQ: " + os.path.basename(package))
                else:
                    resource_map.append((package, False))
                    print("\nLoaded folder patch: " + os.path.basename(package))

            print("\nDone initializing data packages.")
            print("Total loading time: ", time.strftime("%M minutes %S seconds", time.gmtime(time.time() - start_time)))
            return resource_map
        else:
            print("\nPath to World of Warcraft is empty or invalid. Failed to load game data.")
            return None
releaseNote.py 文件源码 项目:releasenote 作者: sveneruso 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def generate(start_release, end_release):
    check_exists(output_folder)
    init(config['repo_path'], end_release, start_release)

    relase_file_name = output_folder + 'release_' + end_release + '.txt'
    f = open(relase_file_name, 'w', encoding='utf8')
    f.write('Release ' + end_release + '\n')
    f.write('\n')
    f.write(strftime('Generated %a, %d %b %Y %H:%M:%S \n', gmtime()))
    f.write('\n')

    for trello in generate_release():
        f.write(trello + '\n')

    f.close()
    config_file.close()
geo.py 文件源码 项目:beastcraft-telemetry 作者: ab77 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def write_db(dbc, rpt, domain=None, key=None):
    l = []
    for measurement, value in rpt.iteritems():
        t = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
        if measurement not in ['class', 'device']:
          json_body = {
              'measurement': measurement,
              'tags': {
                  'class': rpt['class'],
                  'device': rpt['device']
              },
              'time': t,
              'fields': {
                  'value': value
              }
          }
          l.append(json_body)

    print('Write points: {0}'.format(l))
    dbc.write_points(l)
    update_dns(coords=rpt['geo'], domain=domain, key=key)
GeneDiseaseBot.py 文件源码 项目:scheduled-bots 作者: SuLab 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def create_references(self, gdr):

        references = []

        # Reference URL for phenocarta
        references.append(wdi_core.WDUrl(value=gdr.phenocarta_url, prop_nr=PROPS['reference URL'], is_reference=True))

        # Reference URL for genome.gov
        references.append(wdi_core.WDUrl(value=gdr.link, prop_nr=PROPS['reference URL'], is_reference=True))

        # Stated in Phenocarta
        references.append(wdi_core.WDItemID(value='Q22330995', prop_nr=PROPS['stated in'], is_reference=True))

        # Stated in PubMed
        references.append(wdi_core.WDItemID(value=self.pmid_qid_map[gdr.pmid], prop_nr=PROPS['stated in'],
                                            is_reference=True))

        # Date retrieved
        references.append(
            wdi_core.WDTime(strftime("+%Y-%m-%dT00:00:00Z", gmtime()), prop_nr=PROPS['retrieved'], is_reference=True))

        return references
__init__.py 文件源码 项目:sndlatr 作者: Schibum 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def request(self, method, request_uri, headers, content):
        """Modify the request headers"""
        keys = _get_end2end_headers(headers)
        keylist = "".join(["%s " % k for k in keys])
        headers_val = "".join([headers[k] for k in keys])
        created = time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime())
        cnonce = _cnonce()
        request_digest = "%s:%s:%s:%s:%s" % (method, request_uri, cnonce, self.challenge['snonce'], headers_val)
        request_digest  = hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower()
        headers['authorization'] = 'HMACDigest username="%s", realm="%s", snonce="%s", cnonce="%s", uri="%s", created="%s", response="%s", headers="%s"' % (
                self.credentials[0],
                self.challenge['realm'],
                self.challenge['snonce'],
                cnonce,
                request_uri,
                created,
                request_digest,
                keylist)
status.py 文件源码 项目:PyTradier 作者: rleonard21 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def timestamp(self, **config):  # returns the timestamp of the last check
        """ Returns the timestamp of the status update. 

            The default style is Unix Epoch time, though using ``style='pretty'`` returns the time in ``YYYY-MM-DD H:M:S``
        """
        response = self._parse_response('timestamp', **config)

        if 'style' in config.keys():
            # user has specified style of time response

            if config['style'] is 'epoch':
                return response  # API returns Unix epoch by default, so return raw response time value

            if config['style'] is 'pretty':  # useful for displaying the timestamp
                return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(response))

        else:
            return response
fingerprints.py 文件源码 项目:darkc0de-old-stuff 作者: tuwid 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def doFingerprints(self, nomfichier) :
        try :
            fichier = open(nomfichier, "w")
        except IOError :
            print "No such file " + nomfichier 
            sys.exit(-1)

        print "++ Begin Generating Fingerprints in " + nomfichier
        fichier.write("# Generating Fingerprints for :\n# ")
        for i in platform.uname():
            fichier.write(i + " ")

        fichier.write('\n')

        temps = strftime('%c', gmtime())
        fichier.write("# " + temps + '\n')

        self.ssyscalls.doFingerprints(fichier)

        fichier.close()
        print "++ Keep this fingerprints in safe !"
        print "++ End Generating Fingerprints"
PsiMarginal.py 文件源码 项目:Psi-staircase 作者: NNiehof 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def meta_data(self):
        import time
        import sys
        metadata = {}
        date = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time()))
        metadata['date'] = date
        metadata['Version'] = self.version
        metadata['Python Version'] = sys.version
        metadata['Numpy Version'] = np.__version__
        metadata['Scipy Version '] = scipy.__version__
        metadata['psyFunction'] = self.psyfun
        metadata['thresholdGrid'] = self.threshold.tolist()
        metadata['thresholdPrior'] = self.thresholdPrior
        metadata['slopeGrid'] = self.slope.tolist()
        metadata['slopePrior'] = self.slopePrior
        metadata['gammaGrid'] = self.guessRate.tolist()
        metadata['gammaPrior'] = self.guessPrior
        metadata['lapseGrid'] = self.lapseRate.tolist()
        metadata['lapsePrior'] = self.lapsePrior
        return metadata
swatch.py 文件源码 项目:pinhook-tilde 作者: archangelic 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def beats():
    '''Swatch beats'''

    t = time.gmtime()
    h, m, s = t.tm_hour, t.tm_min, t.tm_sec

    utc = 3600 * h + 60 * m + s  # UTC

    bmt = utc + 3600  # Biel Mean Time (BMT)

    beat = bmt / 86.4

    if beat > 1000:
        beat -= 1000

    return beat
nntp.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def fetchNewNews(self, groups, date, distributions = ''):
        """
        Get the Message-IDs for all new news posted to any of the given
        groups since the specified date - in seconds since the epoch, GMT -
        optionally restricted to the given distributions.  gotNewNews() is
        called on success, getNewNewsFailed() on failure.

        One invocation of this function may result in multiple invocations
        of gotNewNews()/getNewNewsFailed().
        """
        date, timeStr = time.strftime('%y%m%d %H%M%S', time.gmtime(date)).split()
        line = 'NEWNEWS %%s %s %s %s' % (date, timeStr, distributions)
        groupPart = ''
        while len(groups) and len(line) + len(groupPart) + len(groups[-1]) + 1 < NNTPClient.MAX_COMMAND_LENGTH:
            group = groups.pop()
            groupPart = groupPart + ',' + group

        self.sendLine(line % (groupPart,))
        self._newState(self._stateNewNews, self.getNewNewsFailed)

        if len(groups):
            self.fetchNewNews(groups, date, distributions)
rfc822.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def formatdate(timeval=None):
    """Returns time format preferred for Internet standards.

    Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123

    According to RFC 1123, day and month names must always be in
    English.  If not for that, this code could use strftime().  It
    can't because strftime() honors the locale and could generated
    non-English names.
    """
    if timeval is None:
        timeval = time.time()
    timeval = time.gmtime(timeval)
    return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (
            ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")[timeval[6]],
            timeval[2],
            ("Jan", "Feb", "Mar", "Apr", "May", "Jun",
             "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")[timeval[1]-1],
                                timeval[0], timeval[3], timeval[4], timeval[5])


# When used as script, run a small test program.
# The first command line argument must be a filename containing one
# message in RFC-822 format.
tarfile.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def __init__(self, file, mode="r", compression=TAR_PLAIN):
        from warnings import warnpy3k
        warnpy3k("the TarFileCompat class has been removed in Python 3.0",
                stacklevel=2)
        if compression == TAR_PLAIN:
            self.tarfile = TarFile.taropen(file, mode)
        elif compression == TAR_GZIPPED:
            self.tarfile = TarFile.gzopen(file, mode)
        else:
            raise ValueError("unknown compression constant")
        if mode[0:1] == "r":
            members = self.tarfile.getmembers()
            for m in members:
                m.filename = m.name
                m.file_size = m.size
                m.date_time = time.gmtime(m.mtime)[:6]
Data.py 文件源码 项目:BlackFridayApp 作者: M4T3U5 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def getSystemData():
        return Data(int(sysdata().tm_mday),int(sysdata().tm_mon),int(sysdata().tm_year))

    ## getters
Data.py 文件源码 项目:BlackFridayApp 作者: M4T3U5 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def getSystemData():
        return Data(int(sysdata().tm_mday),int(sysdata().tm_mon),int(sysdata().tm_year))

    ## getters
FunctionCommon.py 文件源码 项目:PhonePerformanceMeasure 作者: KyleCe 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def current_time():
    return strftime(Res.time_format, gmtime())
dnsdb_query.py 文件源码 项目:Cortex-Analyzers 作者: CERT-BDF 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def sec_to_text(ts):
    return time.strftime('%Y-%m-%d %H:%M:%S -0000', time.gmtime(ts))
out.py 文件源码 项目:txt2evernote 作者: Xunius 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def showUser(user, fullInfo):
    def line(key, value):
        if value:
            printLine("%s : %s" % (key.ljust(16, " "), value))

    separator("#", "USER INFO")
    line('Username', user.username)
    line('Name', user.name)
    line('Email', user.email)

    if fullInfo:
        limit = (int(user.accounting.uploadLimit) / 1024 / 1024)
        endlimit = time.gmtime(user.accounting.uploadLimitEnd / 1000)
        line('Upload limit', "%.2f" % limit)
        line('Upload limit end', time.strftime("%d.%m.%Y", endlimit))
util.py 文件源码 项目:python- 作者: secondtonone1 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def format_duration(self, duration):
        if (duration <= 0) and self.max is None or self.cur == self.min:
            result = '??:??:??'
        #elif duration < 1:
        #    result = '--:--:--'
        else:
            result = time.strftime('%H:%M:%S', time.gmtime(duration))
        return result


问题


面经


文章

微信
公众号

扫码关注公众号