Python time.gmtime() Examples

The following are code examples for showing how to use time.gmtime(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: core-framework   Author: RedhawkSDR   File: test_13_SDDS.py    (license) View Source Project 6 votes vote down vote up
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 ) 
Example 2
Project: kinect-2-libras   Author: inessadl   File: rfc822.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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. 
Example 3
Project: kinect-2-libras   Author: inessadl   File: tarfile.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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] 
Example 4
Project: kinect-2-libras   Author: inessadl   File: utils.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <[email protected]>

    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.
    """
    timeval = time.time()
    utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
    pid = os.getpid()
    randint = random.randrange(100000)
    if idstring is None:
        idstring = ''
    else:
        idstring = '.' + idstring
    idhost = socket.getfqdn()
    msgid = '<%s.%s.%s%[email protected]%s>' % (utcdate, pid, randint, idstring, idhost)
    return msgid



# These functions are in the standalone mimelib version only because they've
# subsequently been fixed in the latest Python versions.  We use this to worm
# around broken older Pythons. 
Example 5
Project: kinect-2-libras   Author: inessadl   File: __init__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def formatTime(self, record, datefmt=None):
        """
        Return the creation time of the specified LogRecord as formatted text.

        This method should be called from format() by a formatter which
        wants to make use of a formatted time. This method can be overridden
        in formatters to provide for any specific requirement, but the
        basic behaviour is as follows: if datefmt (a string) is specified,
        it is used with time.strftime() to format the creation time of the
        record. Otherwise, the ISO8601 format is used. The resulting
        string is returned. This function uses a user-configurable function
        to convert the creation time to a tuple. By default, time.localtime()
        is used; to change this for a particular formatter instance, set the
        'converter' attribute to a function with the same signature as
        time.localtime() or time.gmtime(). To change it for all formatters,
        for example if you want all logging times to be shown in GMT,
        set the 'converter' attribute in the Formatter class.
        """
        ct = self.converter(record.created)
        if datefmt:
            s = time.strftime(datefmt, ct)
        else:
            t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
            s = "%s,%03d" % (t, record.msecs)
        return s 
Example 6
Project: kinect-2-libras   Author: inessadl   File: Cookie.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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.
# 
Example 7
Project: kinect-2-libras   Author: inessadl   File: mailbox.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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) 
Example 8
Project: sea-lion-counter   Author: rdinse   File: main.py    (license) View Source Project 6 votes vote down vote up
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']) 
Example 9
Project: otRebuilder   Author: Pal3love   File: timeTools.py    (MIT License) View Source Project 6 votes vote down vote up
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 
Example 10
Project: oscars2016   Author: 0x0ece   File: __init__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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) 
Example 11
Project: cfpp   Author: dcoker   File: extrinsics.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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) 
Example 12
Project: PyExPool   Author: eXascaleInfolab   File: mpepool.py    (license) View Source Project 6 votes vote down vote up
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 
Example 13
Project: Flask_Blog   Author: sugarguo   File: utils.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <[email protected]>

    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.
    """
    timeval = time.time()
    utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
    pid = os.getpid()
    randint = random.randrange(100000)
    if idstring is None:
        idstring = ''
    else:
        idstring = '.' + idstring
    idhost = socket.getfqdn()
    msgid = '<%s.%s.%s%[email protected]%s>' % (utcdate, pid, randint, idstring, idhost)
    return msgid



# These functions are in the standalone mimelib version only because they've
# subsequently been fixed in the latest Python versions.  We use this to worm
# around broken older Pythons. 
Example 14
Project: Blender-WMO-import-export-scripts   Author: WowDevTools   File: wmo_file.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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))) 
Example 15
Project: Blender-WMO-import-export-scripts   Author: WowDevTools   File: wow.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 16
Project: releasenote   Author: sveneruso   File: releaseNote.py    (MIT License) View Source Project 6 votes vote down vote up
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() 
Example 17
Project: beastcraft-telemetry   Author: ab77   File: geo.py    (MIT License) View Source Project 6 votes vote down vote up
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) 
Example 18
Project: scheduled-bots   Author: SuLab   File: GeneDiseaseBot.py    (license) View Source Project 6 votes vote down vote up
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 
Example 19
Project: sndlatr   Author: Schibum   File: __init__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
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) 
Example 20
Project: PyTradier   Author: rleonard21   File: status.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 21
Project: darkc0de-old-stuff   Author: tuwid   File: fingerprints.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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" 
Example 22
Project: Psi-staircase   Author: NNiehof   File: PsiMarginal.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
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 
Example 23
Project: pinhook-tilde   Author: archangelic   File: swatch.py    (license) View Source Project 6 votes vote down vote up
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 
Example 24
Project: hostapd-mana   Author: adde88   File: nntp.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 25
Project: hostapd-mana   Author: adde88   File: smtp.py    (license) View Source Project 6 votes vote down vote up
def messageid(uniq=None, N=idGenerator().next):
    """Return a globally unique random string in RFC 2822 Message-ID format

    <[email protected]>

    Optional uniq string will be added to strenghten uniqueness if given.
    """
    datetime = time.strftime('%Y%m%d%H%M%S', time.gmtime())
    pid = os.getpid()
    rand = random.randrange(2**31L-1)
    if uniq is None:
        uniq = ''
    else:
        uniq = '.' + uniq

    return '<%s.%s.%s%s.%[email protected]%s>' % (datetime, pid, rand, uniq, N(), DNSNAME) 
Example 26
Project: hostapd-mana   Author: adde88   File: rfc822.py    (license) View Source Project 6 votes vote down vote up
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. 
Example 27
Project: hostapd-mana   Author: adde88   File: tarfile.py    (license) View Source Project 6 votes vote down vote up
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] 
Example 28
Project: hostapd-mana   Author: adde88   File: utils.py    (license) View Source Project 6 votes vote down vote up
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <[email protected]>

    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.
    """
    timeval = time.time()
    utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
    pid = os.getpid()
    randint = random.randrange(100000)
    if idstring is None:
        idstring = ''
    else:
        idstring = '.' + idstring
    idhost = socket.getfqdn()
    msgid = '<%s.%s.%s%[email protected]%s>' % (utcdate, pid, randint, idstring, idhost)
    return msgid



# These functions are in the standalone mimelib version only because they've
# subsequently been fixed in the latest Python versions.  We use this to worm
# around broken older Pythons. 
Example 29
Project: BlackFridayApp   Author: M4T3U5   File: Data.py    (license) View Source Project 5 votes vote down vote up
def getSystemData():
		return Data(int(sysdata().tm_mday),int(sysdata().tm_mon),int(sysdata().tm_year))
		
	## getters 
Example 30
Project: BlackFridayApp   Author: M4T3U5   File: Data.py    (license) View Source Project 5 votes vote down vote up
def getSystemData():
		return Data(int(sysdata().tm_mday),int(sysdata().tm_mon),int(sysdata().tm_year))
		
	## getters 
Example 31
Project: PhonePerformanceMeasure   Author: KyleCe   File: FunctionCommon.py    (MIT License) View Source Project 5 votes vote down vote up
def current_time():
    return strftime(Res.time_format, gmtime()) 
Example 32
Project: Cortex-Analyzers   Author: CERT-BDF   File: dnsdb_query.py    (license) View Source Project 5 votes vote down vote up
def sec_to_text(ts):
    return time.strftime('%Y-%m-%d %H:%M:%S -0000', time.gmtime(ts)) 
Example 33
Project: txt2evernote   Author: Xunius   File: out.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
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)) 
Example 34
Project: python-   Author: secondtonone1   File: util.py    (license) View Source Project 5 votes vote down vote up
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 
Example 35
Project: python-   Author: secondtonone1   File: heuristics.py    (license) View Source Project 5 votes vote down vote up
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))} 
Example 36
Project: my-first-blog   Author: AnkurBegining   File: util.py    (license) View Source Project 5 votes vote down vote up
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 
Example 37
Project: my-first-blog   Author: AnkurBegining   File: heuristics.py    (license) View Source Project 5 votes vote down vote up
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))} 
Example 38
Project: docker-monitoring-zabbix-agent   Author: digiapulssi   File: discover.py    (MIT License) View Source Project 5 votes vote down vote up
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") 
Example 39
Project: core-framework   Author: RedhawkSDR   File: test_11_JavaProperties.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 40
Project: core-framework   Author: RedhawkSDR   File: test_13_SDDS.py    (license) View Source Project 5 votes vote down vote up
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) ) 
Example 41
Project: core-framework   Author: RedhawkSDR   File: test_11_PyProperties.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 42
Project: core-framework   Author: RedhawkSDR   File: test_11_CppProperties.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 43
Project: core-framework   Author: RedhawkSDR   File: sdds_time.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 44
Project: core-framework   Author: RedhawkSDR   File: helpers.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 45
Project: core-framework   Author: RedhawkSDR   File: timestamp.py    (license) View Source Project 5 votes vote down vote up
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 
Example 46
Project: core-framework   Author: RedhawkSDR   File: timestamp.py    (license) View Source Project 5 votes vote down vote up
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 
Example 47
Project: data_pipeline   Author: Yelp   File: tailer.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 48
Project: kinect-2-libras   Author: inessadl   File: BaseHTTPServer.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
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 
Example 49
Project: kinect-2-libras   Author: inessadl   File: cookielib.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
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) 
Example 50
Project: kinect-2-libras   Author: inessadl   File: mailbox.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
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_