Python time 模块,gmtime() 实例源码

我们从Python开源项目中,提取了以下46个代码示例,用于说明如何使用time.gmtime()

项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
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 )
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
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.
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
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]
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
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
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
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.
#
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
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)
项目:sea-lion-counter    作者:rdinse    | 项目源码 | 文件源码
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'])
项目:otRebuilder    作者:Pal3love    | 项目源码 | 文件源码
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
项目:oscars2016    作者:0x0ece    | 项目源码 | 文件源码
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)
项目:cfpp    作者:dcoker    | 项目源码 | 文件源码
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)
项目:PyExPool    作者:eXascaleInfolab    | 项目源码 | 文件源码
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
项目:Blender-WMO-import-export-scripts    作者:WowDevTools    | 项目源码 | 文件源码
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)))
项目:Blender-WMO-import-export-scripts    作者:WowDevTools    | 项目源码 | 文件源码
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    作者:sveneruso    | 项目源码 | 文件源码
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()
项目:beastcraft-telemetry    作者:ab77    | 项目源码 | 文件源码
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)
项目:scheduled-bots    作者:SuLab    | 项目源码 | 文件源码
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
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
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)
项目:PyTradier    作者:rleonard21    | 项目源码 | 文件源码
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
项目:darkc0de-old-stuff    作者:tuwid    | 项目源码 | 文件源码
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"
项目:Psi-staircase    作者:NNiehof    | 项目源码 | 文件源码
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
项目:pinhook-tilde    作者:archangelic    | 项目源码 | 文件源码
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
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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.
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
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]
项目:BlackFridayApp    作者:M4T3U5    | 项目源码 | 文件源码
def getSystemData():
        return Data(int(sysdata().tm_mday),int(sysdata().tm_mon),int(sysdata().tm_year))

    ## getters
项目:BlackFridayApp    作者:M4T3U5    | 项目源码 | 文件源码
def getSystemData():
        return Data(int(sysdata().tm_mday),int(sysdata().tm_mon),int(sysdata().tm_year))

    ## getters
项目:PhonePerformanceMeasure    作者:KyleCe    | 项目源码 | 文件源码
def current_time():
    return strftime(Res.time_format, gmtime())
项目:Cortex-Analyzers    作者:CERT-BDF    | 项目源码 | 文件源码
def sec_to_text(ts):
    return time.strftime('%Y-%m-%d %H:%M:%S -0000', time.gmtime(ts))
项目:txt2evernote    作者:Xunius    | 项目源码 | 文件源码
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))
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
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
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
def update_headers(self, resp):
        headers = resp.headers

        if 'expires' in headers:
            return {}

        if 'cache-control' in headers and headers['cache-control'] != 'public':
            return {}

        if resp.status not in self.cacheable_by_default_statuses:
            return {}

        if 'date' not in headers or 'last-modified' not in headers:
            return {}

        date = calendar.timegm(parsedate_tz(headers['date']))
        last_modified = parsedate(headers['last-modified'])
        if date is None or last_modified is None:
            return {}

        now = time.time()
        current_age = max(0, now - date)
        delta = date - calendar.timegm(last_modified)
        freshness_lifetime = max(0, min(delta / 10, 24 * 3600))
        if freshness_lifetime <= current_age:
            return {}

        expires = date + freshness_lifetime
        return {'expires': time.strftime(TIME_FMT, time.gmtime(expires))}
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
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
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
def update_headers(self, resp):
        headers = resp.headers

        if 'expires' in headers:
            return {}

        if 'cache-control' in headers and headers['cache-control'] != 'public':
            return {}

        if resp.status not in self.cacheable_by_default_statuses:
            return {}

        if 'date' not in headers or 'last-modified' not in headers:
            return {}

        date = calendar.timegm(parsedate_tz(headers['date']))
        last_modified = parsedate(headers['last-modified'])
        if date is None or last_modified is None:
            return {}

        now = time.time()
        current_age = max(0, now - date)
        delta = date - calendar.timegm(last_modified)
        freshness_lifetime = max(0, min(delta / 10, 24 * 3600))
        if freshness_lifetime <= current_age:
            return {}

        expires = date + freshness_lifetime
        return {'expires': time.strftime(TIME_FMT, time.gmtime(expires))}
项目:docker-monitoring-zabbix-agent    作者:digiapulssi    | 项目源码 | 文件源码
def debug(output):
    if _DEBUG:
        if not "debuglog" in globals():
            global debuglog
            debuglog = open("debuglog","a")
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S : ", time.gmtime())
        debuglog.write(timestamp + str(output)+"\n")
项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
def test_UTCTimeJava(self):
        prop = self._app.query([CF.DataType('simple_utctime', any.to_any(None))])
        datetime = time.gmtime(prop[0].value.value().twsec)
        self.assertEquals(datetime.tm_year,2017)
        self.assertEquals(datetime.tm_mon,2)
        self.assertEquals(datetime.tm_mday,1)
        self.assertEquals(datetime.tm_hour,10)
        self.assertEquals(datetime.tm_min,1)
        self.assertEquals(datetime.tm_sec,0)
        self.assertEquals(prop[0].value.value().tfsec,0.123)
        self._app.configure([CF.DataType('reset_utctime', any.to_any(True))])
        prop = self._app.query([CF.DataType('simple_utctime', any.to_any(None))])
        now = time.time()
        self.assertEquals(abs(now-(prop[0].value.value().twsec+prop[0].value.value().tfsec))<0.1,True)
项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
def test_startofyear(self):
        sdds_soy = Time.startOfYear()

        # calculate start of year
        soy = datetime.datetime(*(time.strptime(self.cur_year_str+"-01-01 00:00:00",
                                         "%Y-%m-%d %H:%M:%S")[0:6]))
        soy_time=calendar.timegm(soy.timetuple())
        self.assertEqual( sdds_soy, soy_time )

        sdds_time = Time()
        sdds_time.setFromTime(soy_time)
        # calculate start of year
        self.assertEqual( sdds_time.gmtime(), time.gmtime(soy_time) )
项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
def test_UTCTimePython(self):
        prop = self._app.query([CF.DataType('simple_utctime', any.to_any(None))])
        datetime = time.gmtime(prop[0].value.value().twsec)
        self.assertEquals(datetime.tm_year,2017)
        self.assertEquals(datetime.tm_mon,2)
        self.assertEquals(datetime.tm_mday,1)
        self.assertEquals(datetime.tm_hour,10)
        self.assertEquals(datetime.tm_min,1)
        self.assertEquals(datetime.tm_sec,0)
        self.assertEquals(prop[0].value.value().tfsec,0.123)
        self._app.configure([CF.DataType('reset_utctime', any.to_any(True))])
        prop = self._app.query([CF.DataType('simple_utctime', any.to_any(None))])
        now = time.time()
        self.assertEquals(abs(now-(prop[0].value.value().twsec+prop[0].value.value().tfsec))<0.1,True)
项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
def test_UTCTime(self):
        prop = self._app.query([CF.DataType('simple_utctime', any.to_any(None))])
        datetime = time.gmtime(prop[0].value.value().twsec)
        self.assertEquals(datetime.tm_year,2017)
        self.assertEquals(datetime.tm_mon,2)
        self.assertEquals(datetime.tm_mday,1)
        self.assertEquals(datetime.tm_hour,10)
        self.assertEquals(datetime.tm_min,1)
        self.assertEquals(datetime.tm_sec,0)
        self.assertEquals(prop[0].value.value().tfsec,0.123)
        self._app.configure([CF.DataType('reset_utctime', any.to_any(True))])
        prop = self._app.query([CF.DataType('simple_utctime', any.to_any(None))])
        now = time.time()
        self.assertEquals(abs(now-(prop[0].value.value().twsec+prop[0].value.value().tfsec))<0.1,True)
项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
def toString(t1, fmt=None):
         gmt = t1.gmtime()
         frac =  int(t1.pf250_ * (Time.Tic/Time.Two32))
         if not fmt:
              fmt = Time.REDHAWK_FORMAT
              xx=time.strftime(fmt,gmt)
              return '%s.%06d' % (xx,frac)
         else:
              return time.strftime(fmt,gmt)
项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
def toString(tstamp):
    # Break out the whole seconds into a GMT time
    gmt = time.gmtime(tstamp.twsec)
    # Append the fractional seconds down to microsecond precision
    fractional = int(round(tstamp.tfsec * 1e6))
    return '%04d:%02d:%02d::%02d:%02d:%02d.%06d' % (gmt.tm_year, gmt.tm_mon, gmt.tm_mday, gmt.tm_hour,
                                                    gmt.tm_min, gmt.tm_sec, fractional)
项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
def toString(tstamp):
    # Break out the whole seconds into a GMT time
    gmt = time.gmtime(tstamp.twsec)
    # Append the fractional seconds down to microsecond precision
    fractional = int(round(tstamp.tfsec * 1e6))
    return '%04d:%02d:%02d::%02d:%02d:%02d.%06d' % (gmt.tm_year, gmt.tm_mon, gmt.tm_mday, gmt.tm_hour,
                                                    gmt.tm_min, gmt.tm_sec, fractional)

# Insert the arithmetic functions as operators on the PrecisionUTCTime class
项目:core-framework    作者:RedhawkSDR    | 项目源码 | 文件源码
def toString(tstamp):
    # Break out the whole seconds into a GMT time
    gmt = time.gmtime(tstamp.twsec)
    # Append the fractional seconds down to microsecond precision
    fractional = int(round(tstamp.tfsec * 1e6))
    return '%04d:%02d:%02d::%02d:%02d:%02d.%06d' % (gmt.tm_year, gmt.tm_mon, gmt.tm_mday, gmt.tm_hour,
                                                    gmt.tm_min, gmt.tm_sec, fractional)

# Insert the arithmetic functions as operators on the PrecisionUTCTime class
项目:data_pipeline    作者:Yelp    | 项目源码 | 文件源码
def _iso_time(self, result_dict):
        def _transform_item_iso_time(key, item):
            if key.startswith('time') and isinstance(item, int):
                return time.strftime(
                    '%Y-%m-%dT%H:%M:%S',
                    time.gmtime(item)
                )
            return item
        self._walk_dict(result_dict, _transform_item_iso_time)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def date_time_string(self, timestamp=None):
        """Return the current date and time formatted for a message header."""
        if timestamp is None:
            timestamp = time.time()
        year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
        s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
                self.weekdayname[wd],
                day, self.monthname[month], year,
                hh, mm, ss)
        return s
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def time2netscape(t=None):
    """Return a string representing time in seconds since epoch, t.

    If the function is called without an argument, it will use the current
    time.

    The format of the returned string is like this:

    Wed, DD-Mon-YYYY HH:MM:SS GMT

    """
    if t is None: t = time.time()
    year, mon, mday, hour, min, sec, wday = time.gmtime(t)[:7]
    return "%s %02d-%s-%04d %02d:%02d:%02d GMT" % (
        DAYS[wday], mday, MONTHS[mon-1], year, hour, min, sec)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def set_from(self, from_, time_=None):
        """Set "From " line, formatting and appending time_ if specified."""
        if time_ is not None:
            if time_ is True:
                time_ = time.gmtime()
            from_ += ' ' + time.asctime(time_)
        self._from = from_