Python time.gmtime() Examples
The following are 30
code examples of time.gmtime().
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 also want to check out all available functions/classes of the module
time
, or try the search function
.
Example #1
Source File: httputil.py From tornado-zh with MIT License | 7 votes |
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
Source File: test_static.py From sanic with MIT License | 6 votes |
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
Source File: httputil.py From tornado-zh with MIT License | 6 votes |
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 #4
Source File: datetime.py From verge3d-blender-addon with GNU General Public License v3.0 | 6 votes |
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 #5
Source File: utils.py From verge3d-blender-addon with GNU General Public License v3.0 | 6 votes |
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 #6
Source File: request.py From verge3d-blender-addon with GNU General Public License v3.0 | 6 votes |
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
Source File: Callbacks.py From GroundedTranslation with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Source File: PortalFiles.py From single_cell_portal with BSD 3-Clause "New" or "Revised" License | 6 votes |
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 #9
Source File: __init__.py From jawfish with MIT License | 6 votes |
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 #10
Source File: converter_snowsql.py From snowflake-connector-python with Apache License 2.0 | 6 votes |
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 #11
Source File: datetime.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
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
Source File: utils.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
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 #13
Source File: utils.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
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 #14
Source File: datetime.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
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 #15
Source File: test_utils.py From python-zhmcclient with Apache License 2.0 | 5 votes |
def x_test_print_gmtime_max(self): """Print the maximum for time.gmtime().""" max_ts = find_max_value(time.gmtime, 1) max_st = time.gmtime(max_ts) print("\nMax Unix timestamp value for Python time.gmtime(): {} ({!r})". format(max_ts, max_st)) sys.stdout.flush()
Example #16
Source File: profiler.py From arches with GNU Affero General Public License v3.0 | 5 votes |
def profile(log_file): """Profile some callable. This decorator uses the hotshot profiler to profile some callable (like a view function or method) and dumps the profile data somewhere sensible for later processing and examination. It takes one argument, the profile log name. If it's a relative path, it places it under the PROFILE_LOG_BASE. It also inserts a time stamp into the file name, such that 'my_view.prof' become 'my_view-20100211T170321.prof', where the time stamp is in UTC. This makes it easy to run and compare multiple trials. """ if not os.path.isabs(log_file): log_file = os.path.join(PROFILE_LOG_BASE, log_file) def _outer(f): def _inner(*args, **kwargs): # Add a timestamp to the profile output when the callable # is actually called. (base, ext) = os.path.splitext(log_file) base = base + "-" + time.strftime("%Y%m%dT%H%M%S", time.gmtime()) final_log_file = base + ext prof = hotshot.Profile(final_log_file) try: ret = prof.runcall(f, *args, **kwargs) finally: prof.close() return ret return _inner return _outer
Example #17
Source File: dump_ocsp_response_cache.py From snowflake-connector-python with Apache License 2.0 | 5 votes |
def raise_outdated_validity_exception( current_time, name, serial_number, this_update, next_update): raise Exception("ERROR: OCSP response cache include " "outdated data: " "name: {}, serial_number: {}, " "current_time: {}, this_update: {}, " "next_update: {}".format( name, serial_number, strftime( SFOCSP.OUTPUT_TIMESTAMP_FORMAT, gmtime(current_time)), this_update.strftime( SFOCSP.OUTPUT_TIMESTAMP_FORMAT), next_update.strftime( SFOCSP.OUTPUT_TIMESTAMP_FORMAT)))
Example #18
Source File: auth_webbrowser.py From snowflake-connector-python with Apache License 2.0 | 5 votes |
def _process_options(self, data, socket_client): """Allows JS Ajax access to this endpoint.""" for line in data: if line.startswith("OPTIONS "): break else: return False self._get_user_agent(data) requested_headers, requested_origin = self._check_post_requested(data) if not requested_headers: return False if not self._validate_origin(requested_origin): # validate Origin and fail if not match with the server. return False self._origin = requested_origin content = [ "HTTP/1.1 200 OK", "Date: {}".format( time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())), "Access-Control-Allow-Methods: POST, GET", "Access-Control-Allow-Headers: {}".format(requested_headers), "Access-Control-Max-Age: 86400", "Access-Control-Allow-Origin: {}".format(self._origin), "", "", ] socket_client.sendall('\r\n'.join(content).encode('utf-8')) return True
Example #19
Source File: test_unit_datetime.py From snowflake-connector-python with Apache License 2.0 | 5 votes |
def test_struct_time_format_extreme_large(): # extreme large epoch time value = SnowflakeDateTime( time.gmtime(14567890123567), nanosecond=0, scale=1) formatter = SnowflakeDateTimeFormat( 'YYYY-MM-DD"T"HH24:MI:SS.FF', datetime_class=SnowflakeDateTime) assert formatter.format(value) == '463608-01-23T09:26:07.0'
Example #20
Source File: httputil_test.py From tornado-zh with MIT License | 5 votes |
def test_struct_time(self): self.check(time.gmtime(self.TIMESTAMP))
Example #21
Source File: test_utils.py From python-zhmcclient with Apache License 2.0 | 5 votes |
def test_gmtime_epoch(self): """Test that time.gmtime() is based upon the UNIX epoch.""" epoch_st = time.struct_time([1970, 1, 1, 0, 0, 0, 3, 1, 0]) st = time.gmtime(0) assert st == epoch_st
Example #22
Source File: test_svnurl.py From py with MIT License | 5 votes |
def test_svn_1_2(self): line = " 2256 hpk 165 Nov 24 17:55 __init__.py" info = InfoSvnCommand(line) now = datetime.datetime.now() assert info.last_author == 'hpk' assert info.created_rev == 2256 assert info.kind == 'file' # we don't check for the year (2006), because that depends # on the clock correctly being setup assert time.gmtime(info.mtime)[1:6] == (11, 24, 17, 55, 0) assert info.size == 165 assert info.time == info.mtime * 1000000
Example #23
Source File: httputil_test.py From tornado-zh with MIT License | 5 votes |
def test_time_tuple(self): tup = tuple(time.gmtime(self.TIMESTAMP)) self.assertEqual(9, len(tup)) self.check(tup)
Example #24
Source File: httputil_test.py From tornado-zh with MIT License | 5 votes |
def test_struct_time(self): self.check(time.gmtime(self.TIMESTAMP))
Example #25
Source File: datetime.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
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 #26
Source File: datetime.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
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 #27
Source File: cookies.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
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 #28
Source File: utils.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
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 #29
Source File: __init__.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers["authorization"] = 'WSSE profile="UsernameToken"' iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1]) headers["X-WSSE"] = ( 'UsernameToken Username="%s", PasswordDigest="%s", ' 'Nonce="%s", Created="%s"' ) % (self.credentials[0], password_digest, cnonce, iso_now)
Example #30
Source File: __init__.py From misp42splunk with GNU Lesser General Public License v3.0 | 5 votes |
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, )