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

如何从接口响应文本中提取expiry对应的纯动态时间戳,去除后续冗余内容

方案1:直接解析JSON响应(最推荐)

接口返回内容是标准JSON格式,无需手动做字符串切片处理,直接用Python内置的json模块解析即可,代码修改如下:

import json

if "\"message\":\"Logged in!\"" in response1.text:
    # 解析JSON响应
    res_json = json.loads(response1.text)
    # 按照JSON层级提取expiry字段,subscriptions为数组,取第一个元素的expiry值
    response_time = res_json["info"]["subscriptions"][0]["expiry"]
    # 原有时间转换逻辑只需加int转换即可运行
    # datetime.datetime.fromtimestamp(int(response_time)).strftime('%Y-%m-%d %H:%M:%S')
    print(f"\n\n{response_time}\n\n")
    embed = discord.Embed(
        description=f"You are successfully logged in!\n\n```Information: {username}{response_time}", 
        colour=COLOR
    )
    await msg.channel.send(embed=embed, delete_after=150)
    return

该方案不需要关心字符串位置,只要JSON结构不变,就算字段顺序调整也能稳定拿到正确值,天然避免多余字符问题。

方案2:字符串截取修正方案(特殊场景下使用)

如果因特殊原因必须用字符串切片处理,可以利用时间戳被双引号包裹的特性,动态查找结束边界,代码修改如下:

if "\"message\":\"Logged in!\"" in response1.text:
    start_idx = response1.text.find("expiry") + 9
    # 查找起始位置之后第一个双引号的位置作为结束边界
    end_idx = response1.text.find('"', start_idx)
    response_time = response1.text[start_idx:end_idx]
    # 后续原有逻辑不变
    print(f"\n\n{response_time}\n\n")
    embed = discord.Embed(
        description=f"You are successfully logged in!\n\n```Information: {username}{response_time}", 
        colour=COLOR
    )
    await msg.channel.send(embed=embed, delete_after=150)
    return

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:54:05