Python time.gmtime() Examples

The following are 30 code examples for showing how to use time.gmtime(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

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

Example 1
Project: tornado-zh   Author: tao12345666333   File: httputil.py    License: MIT License 7 votes vote down vote up
def format_timestamp(ts):
    """Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    """
    if isinstance(ts, numbers.Real):
        pass
    elif isinstance(ts, (tuple, time.struct_time)):
        ts = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        ts = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(ts, usegmt=True) 
Example 2
Project: sanic   Author: huge-success   File: test_static.py    License: MIT License 6 votes vote down vote up
def test_use_modified_since(app, static_file_directory, file_name):

    file_stat = os.stat(get_file_path(static_file_directory, file_name))
    modified_since = strftime(
        "%a, %d %b %Y %H:%M:%S GMT", gmtime(file_stat.st_mtime)
    )

    app.static(
        "/testing.file",
        get_file_path(static_file_directory, file_name),
        use_modified_since=True,
    )

    request, response = app.test_client.get(
        "/testing.file", headers={"If-Modified-Since": modified_since}
    )

    assert response.status == 304 
Example 3
Project: jawfish   Author: war-and-code   File: __init__.py    License: MIT License 6 votes vote down vote up
def formatTime(self, record, datefmt=None):
        """
        Return the creation time of the specified LogRecord as formatted text.

        This method should be called from format() by a formatter which
        wants to make use of a formatted time. This method can be overridden
        in formatters to provide for any specific requirement, but the
        basic behaviour is as follows: if datefmt (a string) is specified,
        it is used with time.strftime() to format the creation time of the
        record. Otherwise, the ISO8601 format is used. The resulting
        string is returned. This function uses a user-configurable function
        to convert the creation time to a tuple. By default, time.localtime()
        is used; to change this for a particular formatter instance, set the
        'converter' attribute to a function with the same signature as
        time.localtime() or time.gmtime(). To change it for all formatters,
        for example if you want all logging times to be shown in GMT,
        set the 'converter' attribute in the Formatter class.
        """
        ct = self.converter(record.created)
        if datefmt:
            s = time.strftime(datefmt, ct)
        else:
            t = time.strftime(self.default_time_format, ct)
            s = self.default_msec_format % (t, record.msecs)
        return s 
Example 4
Project: verge3d-blender-addon   Author: Soft8Soft   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def make_msgid(idstring=None, domain=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <20020201195627.33539.96671@nightshade.la.mastaler.com>

    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.  Optional domain if given provides the
    portion of the message id after the '@'.  It defaults to the locally
    defined hostname.
    """
    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
    if domain is None:
        domain = socket.getfqdn()
    msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, domain)
    return msgid 
Example 5
Project: verge3d-blender-addon   Author: Soft8Soft   File: datetime.py    License: GNU General Public License v3.0 6 votes vote down vote up
def utcfromtimestamp(cls, t):
        "Construct a UTC datetime from a POSIX timestamp (like time.time())."
        t, frac = divmod(t, 1.0)
        us = int(frac * 1e6)

        # If timestamp is less than one microsecond smaller than a
        # full second, us can be rounded up to 1000000.  In this case,
        # roll over to seconds, otherwise, ValueError is raised
        # by the constructor.
        if us == 1000000:
            t += 1
            us = 0
        y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
        ss = min(ss, 59)    # clamp out leap seconds if the platform has them
        return cls(y, m, d, hh, mm, ss, us)

    # XXX This is supposed to do better than we *can* do by using time.time(),
    # XXX if the platform supports a more accurate way.  The C implementation
    # XXX uses gettimeofday on platforms that have it, but that isn't
    # XXX available from Python.  So now() may return different results
    # XXX across the implementations. 
Example 6
Project: verge3d-blender-addon   Author: Soft8Soft   File: request.py    License: GNU General Public License v3.0 6 votes vote down vote up
def open_data(self, url, data=None):
        """Use "data" URL."""
        if not isinstance(url, str):
            raise URLError('data error: proxy support for data protocol currently not implemented')
        # ignore POSTed data
        #
        # syntax of data URLs:
        # dataurl   := "data:" [ mediatype ] [ ";base64" ] "," data
        # mediatype := [ type "/" subtype ] *( ";" parameter )
        # data      := *urlchar
        # parameter := attribute "=" value
        try:
            [type, data] = url.split(',', 1)
        except ValueError:
            raise IOError('data error', 'bad data URL')
        if not type:
            type = 'text/plain;charset=US-ASCII'
        semi = type.rfind(';')
        if semi >= 0 and '=' not in type[semi:]:
            encoding = type[semi+1:]
            type = type[:semi]
        else:
            encoding = ''
        msg = []
        msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                            time.gmtime(time.time())))
        msg.append('Content-type: %s' % type)
        if encoding == 'base64':
            # XXX is this encoding/decoding ok?
            data = base64.decodebytes(data.encode('ascii')).decode('latin-1')
        else:
            data = unquote(data)
        msg.append('Content-Length: %d' % len(data))
        msg.append('')
        msg.append(data)
        msg = '\n'.join(msg)
        headers = email.message_from_string(msg)
        f = io.StringIO(msg)
        #f.fileno = None     # needed for addinfourl
        return addinfourl(f, headers, url) 
Example 7
Project: GroundedTranslation   Author: elliottd   File: Callbacks.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def on_epoch_end(self, epoch, logs={}):
        '''
        At the end of each epoch we
          1. create a directory to checkpoint data
          2. save the arguments used to initialise the run
          3. generate N sentences in the val data by sampling from the model
          4. calculate metric score of the generated sentences
          5. determine whether to stop training and sys.exit(0)
          6. save the model parameters using BLEU
        '''
        savetime = strftime("%d%m%Y-%H%M%S", gmtime())
        path = self.create_checkpoint_directory(savetime)
        self.save_run_arguments(path)

        # Generate training and val sentences to check for overfitting
        self.generate_sentences(path)
        meteor, bleu, ter = self.multeval_scores(path)
        val_loss = logs.get('val_loss')

        self.early_stop_decision(len(self.val_metric)+1, meteor, val_loss)
        self.checkpoint_parameters(epoch, logs, path, meteor, val_loss)
        self.log_performance() 
Example 8
Project: misp42splunk   Author: remg427   File: utils.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def make_msgid(idstring=None, domain=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <20020201195627.33539.96671@nightshade.la.mastaler.com>

    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.  Optional domain if given provides the
    portion of the message id after the '@'.  It defaults to the locally
    defined hostname.
    """
    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
    if domain is None:
        domain = socket.getfqdn()
    msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, domain)
    return msgid 
Example 9
Project: misp42splunk   Author: remg427   File: datetime.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def utcfromtimestamp(cls, t):
        "Construct a UTC datetime from a POSIX timestamp (like time.time())."
        t, frac = divmod(t, 1.0)
        us = int(frac * 1e6)

        # If timestamp is less than one microsecond smaller than a
        # full second, us can be rounded up to 1000000.  In this case,
        # roll over to seconds, otherwise, ValueError is raised
        # by the constructor.
        if us == 1000000:
            t += 1
            us = 0
        y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
        ss = min(ss, 59)    # clamp out leap seconds if the platform has them
        return cls(y, m, d, hh, mm, ss, us)

    # XXX This is supposed to do better than we *can* do by using time.time(),
    # XXX if the platform supports a more accurate way.  The C implementation
    # XXX uses gettimeofday on platforms that have it, but that isn't
    # XXX available from Python.  So now() may return different results
    # XXX across the implementations. 
Example 10
Project: misp42splunk   Author: remg427   File: utils.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def make_msgid(idstring=None, domain=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <20020201195627.33539.96671@nightshade.la.mastaler.com>

    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.  Optional domain if given provides the
    portion of the message id after the '@'.  It defaults to the locally
    defined hostname.
    """
    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
    if domain is None:
        domain = socket.getfqdn()
    msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, domain)
    return msgid 
Example 11
Project: misp42splunk   Author: remg427   File: datetime.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def utcfromtimestamp(cls, t):
        "Construct a UTC datetime from a POSIX timestamp (like time.time())."
        t, frac = divmod(t, 1.0)
        us = int(frac * 1e6)

        # If timestamp is less than one microsecond smaller than a
        # full second, us can be rounded up to 1000000.  In this case,
        # roll over to seconds, otherwise, ValueError is raised
        # by the constructor.
        if us == 1000000:
            t += 1
            us = 0
        y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
        ss = min(ss, 59)    # clamp out leap seconds if the platform has them
        return cls(y, m, d, hh, mm, ss, us)

    # XXX This is supposed to do better than we *can* do by using time.time(),
    # XXX if the platform supports a more accurate way.  The C implementation
    # XXX uses gettimeofday on platforms that have it, but that isn't
    # XXX available from Python.  So now() may return different results
    # XXX across the implementations. 
Example 12
Project: tornado-zh   Author: tao12345666333   File: httputil.py    License: MIT License 6 votes vote down vote up
def format_timestamp(ts):
    """Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    """
    if isinstance(ts, numbers.Real):
        pass
    elif isinstance(ts, (tuple, time.struct_time)):
        ts = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        ts = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(ts, usegmt=True) 
Example 13
Project: single_cell_portal   Author: broadinstitute   File: PortalFiles.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_safe_file_name(self,file_name):
        """
        Using a given file name
        create a new file name that is unique
        so collisions do not occur.
        """

        if not file_name:
            return(None)

        file_pieces = file_name.split(".")
        file_base = file_pieces[0]
        file_ext = ".".join(file_pieces[1:])
        current_time = time.strftime("%Y_%m_%d_%H_%M_%S",time.gmtime())
        new_file_name = file_base + "_" + current_time + "." + file_ext

        if os.path.exists(new_file_name):
            print(" ".join(["ERROR!\tCan not find a safe file name, ",
                            "the file to be written already exists. ",
                            "Please move or rename the file:",
                            os.path.abspath(new_file_name)]))
            return(None)
        return(new_file_name) 
Example 14
Project: snowflake-connector-python   Author: snowflakedb   File: converter_snowsql.py    License: Apache License 2.0 6 votes vote down vote up
def _TIMESTAMP_NTZ_to_python(self, ctx):
        """Converts TIMESTAMP NTZ to Snowflake Formatted String.

        No timezone info is attached.
        """
        def conv(value):
            microseconds, fraction_of_nanoseconds = \
                _extract_timestamp(value, ctx)
            try:
                t = time.gmtime(microseconds)
            except (OSError, ValueError) as e:
                logger.debug(
                    "OSError occurred but falling back to datetime: %s", e)
                t = ZERO_EPOCH + timedelta(seconds=(microseconds))
            return format_sftimestamp(ctx, t, fraction_of_nanoseconds)

        return conv 
Example 15
Project: cherrypy   Author: cherrypy   File: cpstats.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def locale_date(v):
    return time.strftime('%c', time.gmtime(v)) 
Example 16
Project: cherrypy   Author: cherrypy   File: cpstats.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def iso_format(v):
    return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(v)) 
Example 17
Project: BiblioPixelAnimations   Author: ManiacalLabs   File: BinaryEpochClock.py    License: MIT License 5 votes vote down vote up
def step(self, amt=1):
        z = calendar.timegm(time.gmtime(time.time()))

        for i in range(32):
            color = self.palette((z & (1 << i)) > 0)
            if self._reverse:
                i = 31 - i

            start = (self._bitSpace + self._bitWidth) * i
            self.layout.fill(color, start, start + self._bitWidth) 
Example 18
Project: InsightAgent   Author: insightfinder   File: getlogs_mysql.py    License: Apache License 2.0 5 votes vote down vote up
def get_sql_query_time(timestamp, timestamp_format):
    if timestamp_format == Constant.NONE:
        return str(timestamp)
    else:
        return "\'" + time.strftime(timestamp_format, time.gmtime(timestamp / 1000.0)) + "\'" 
Example 19
Project: InsightAgent   Author: insightfinder   File: get_logs_mssql.py    License: Apache License 2.0 5 votes vote down vote up
def get_sql_query_time(timestamp, timestamp_format):
    if timestamp_format == Constant.NONE:
        return str(timestamp)
    else:
        return "\'" + time.strftime(timestamp_format, time.gmtime(timestamp / 1000.0)) + "\'" 
Example 20
Project: todxpy   Author: xypnox   File: fabric.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, createTime=time.gmtime()):
        self.createTime = createTime
        self.username = ''
        self.cookie = ''
        self.tlist = [] 
Example 21
Project: glazier   Author: google   File: installer.py    License: Apache License 2.0 5 votes vote down vote up
def Run(self):
    duration = int(self._args[0])
    converted_time = time.strftime('%H:%M:%S', time.gmtime(duration))

    if len(self._args) > 1:
      logging.info('Sleeping for %s (%s).', converted_time, str(self._args[1]))
    else:
      logging.info('Sleeping for %s before continuing...', converted_time)
    time.sleep(duration) 
Example 22
Project: rtp_cluster   Author: sippy   File: MonoTime.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def ftime(self, base = None):
        if base != None:
            realt = base.realt - (base.monot - self.monot)
        else:
            realt = self.realt
        return strftime('%Y-%m-%d %H:%M:%S+00', gmtime(round(realt))) 
Example 23
Project: rtp_cluster   Author: sippy   File: MonoTime.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def frtime(self, base = None):
        if base != None:
            realt = base.realt - (base.monot - self.monot)
        else:
            realt = self.realt
        gt = gmtime(realt)
        day = strftime('%d', gt)
        if day[0] == '0':
            day = day[1]
        return strftime('%%H:%%M:%%S.000 GMT %%a %%b %s %%Y' % day, gt) 
Example 24
Project: jawfish   Author: war-and-code   File: cookies.py    License: MIT License 5 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) 
Example 25
Project: jawfish   Author: war-and-code   File: datetime.py    License: MIT License 5 votes vote down vote up
def fromtimestamp(cls, t, tz=None):
        """Construct a datetime from a POSIX timestamp (like time.time()).

        A timezone info object may be passed in as well.
        """

        _check_tzinfo_arg(tz)

        converter = _time.localtime if tz is None else _time.gmtime

        t, frac = divmod(t, 1.0)
        us = int(frac * 1e6)

        # If timestamp is less than one microsecond smaller than a
        # full second, us can be rounded up to 1000000.  In this case,
        # roll over to seconds, otherwise, ValueError is raised
        # by the constructor.
        if us == 1000000:
            t += 1
            us = 0
        y, m, d, hh, mm, ss, weekday, jday, dst = converter(t)
        ss = min(ss, 59)    # clamp out leap seconds if the platform has them
        result = cls(y, m, d, hh, mm, ss, us, tz)
        if tz is not None:
            result = tz.fromutc(result)
        return result 
Example 26
Project: jawfish   Author: war-and-code   File: datetime.py    License: MIT License 5 votes vote down vote up
def utctimetuple(self):
        "Return UTC time tuple compatible with time.gmtime()."
        offset = self.utcoffset()
        if offset:
            self -= offset
        y, m, d = self.year, self.month, self.day
        hh, mm, ss = self.hour, self.minute, self.second
        return _build_struct_time(y, m, d, hh, mm, ss, 0) 
Example 27
Project: verge3d-blender-addon   Author: Soft8Soft   File: utils.py    License: GNU General Public License v3.0 5 votes vote down vote up
def localtime(dt=None, isdst=-1):
    """Return local time as an aware datetime object.

    If called without arguments, return current time.  Otherwise *dt*
    argument should be a datetime instance, and it is converted to the
    local time zone according to the system time zone database.  If *dt* is
    naive (that is, dt.tzinfo is None), it is assumed to be in local time.
    In this case, a positive or zero value for *isdst* causes localtime to
    presume initially that summer time (for example, Daylight Saving Time)
    is or is not (respectively) in effect for the specified time.  A
    negative value for *isdst* causes the localtime() function to attempt
    to divine whether summer time is in effect for the specified time.

    """
    if dt is None:
        return datetime.datetime.now(datetime.timezone.utc).astimezone()
    if dt.tzinfo is not None:
        return dt.astimezone()
    # We have a naive datetime.  Convert to a (localtime) timetuple and pass to
    # system mktime together with the isdst hint.  System mktime will return
    # seconds since epoch.
    tm = dt.timetuple()[:-1] + (isdst,)
    seconds = time.mktime(tm)
    localtm = time.localtime(seconds)
    try:
        delta = datetime.timedelta(seconds=localtm.tm_gmtoff)
        tz = datetime.timezone(delta, localtm.tm_zone)
    except AttributeError:
        # Compute UTC offset and compare with the value implied by tm_isdst.
        # If the values match, use the zone name implied by tm_isdst.
        delta = dt - datetime.datetime(*time.gmtime(seconds)[:6])
        dst = time.daylight and localtm.tm_isdst > 0
        gmtoff = -(time.altzone if dst else time.timezone)
        if delta == datetime.timedelta(seconds=gmtoff):
            tz = datetime.timezone(delta, time.tzname[dst])
        else:
            tz = datetime.timezone(delta)
    return dt.replace(tzinfo=tz) 
Example 28
Project: verge3d-blender-addon   Author: Soft8Soft   File: server.py    License: GNU General Public License v3.0 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 29
Project: verge3d-blender-addon   Author: Soft8Soft   File: cookies.py    License: GNU General Public License v3.0 5 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) 
Example 30
Project: verge3d-blender-addon   Author: Soft8Soft   File: datetime.py    License: GNU General Public License v3.0 5 votes vote down vote up
def utctimetuple(self):
        "Return UTC time tuple compatible with time.gmtime()."
        offset = self.utcoffset()
        if offset:
            self -= offset
        y, m, d = self.year, self.month, self.day
        hh, mm, ss = self.hour, self.minute, self.second
        return _build_struct_time(y, m, d, hh, mm, ss, 0)