You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3脚本如何查看各请求发送时间并输出至终端?

记录Python请求的发送时间并显示在终端

作为Python新手,其实你找对方向啦——time或者datetime模块完全能解决这个问题,可能只是没把时间记录和请求发送的时机结合起来。下面给你几个实用的方案,不管用requests还是标准库的urllib都能搞定:

方法一:用datetime模块生成可读时间戳(推荐)

datetime能直接生成人类易读的时间格式,比如年-月-日 时:分:秒.毫秒,非常适合终端显示。结合最常用的requests库,示例代码如下:

from datetime import datetime
import requests

def send_and_log_request(method, url, **kwargs):
    # 记录请求发送的瞬间时间(保留三位毫秒)
    send_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
    print(f"[{send_time}] 发送 {method.upper()} 请求到: {url}")
    
    # 执行对应类型的请求
    if method.lower() == "get":
        response = requests.get(url, **kwargs)
    elif method.lower() == "post":
        response = requests.post(url, **kwargs)
    # 可按需扩展PUT、DELETE等其他请求方法
    
    # 可选:打印请求完成状态
    print(f"[{send_time}] {method.upper()} 请求完成,状态码: {response.status_code}\n")
    return response

# 测试发送不同请求
send_and_log_request("get", "https://httpbin.org/get")
send_and_log_request("post", "https://httpbin.org/post", data={"username": "test_user"})
send_and_log_request("get", "https://httpbin.org/headers")

运行脚本后,终端会清晰显示每个请求的发送时间,格式直观易懂。

方法二:用time模块实现(轻量简洁)

如果你更倾向于用time模块,也可以这样做——先获取时间戳,再转成可读格式:

import time
import requests

def send_with_time_log(method, url, **kwargs):
    # 获取时间戳
    timestamp = time.time()
    # 转换为人类可读的时间字符串
    send_time = time.ctime(timestamp)
    print(f"[{send_time}] 发起 {method.upper()} 请求: {url}")
    
    # 执行请求
    if method.lower() == "get":
        resp = requests.get(url, **kwargs)
    
    print(f"[{send_time}] 请求结束,状态码: {resp.status_code}\n")
    return resp

# 调用示例
send_with_time_log("get", "https://example.com")

这个方案更轻量,适合不需要毫秒级精度的场景。

关键注意点

  • 一定要在调用请求函数的前一刻记录时间,这样才是最准确的请求发送时间,避免被其他代码的执行时间干扰。
  • 如果用标准库的urllib而非requests,逻辑完全一致——只需把requests.get/post替换成urllib.request.urlopen等方法,时间记录的代码保持不变。

内容的提问来源于stack exchange,提问作者Matteo Rizzolo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:42:40