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

Discord Bot使用strftime时小时始终显示为00的问题求助

Discord Bot时间戳小时显示异常修复

你的问题出在ctx.message.created_at是UTC时区的时间,直接用strftime输出的是UTC时间的小时,和你要的本地时区小时不匹配,所以才会出现分钟秒正常、小时始终为00的情况。

快速修复代码

把UTC时间转成本地时区再格式化:

@bot.command()
async def start(ctx):
    if session.is_active:
        await ctx.send("Always look to the future!")
        return
    
    session.is_active = True
    session.start_time = ctx.message.created_at.timestamp()
    # 转换为当前运行环境的本地时区
    local_time = ctx.message.created_at.astimezone()
    human_readable_time = local_time.strftime("%H:%M:%S")
    positive_reminder.start()
    await ctx.send("Positive thoughts fuel a positive mind. Started at {}".format(human_readable_time))

如果需要固定时区(比如国内东八区),可以用pytz库实现:

import pytz

# ...
# 转换为东八区时间
cn_time = ctx.message.created_at.astimezone(pytz.timezone('Asia/Shanghai'))
human_readable_time = cn_time.strftime("%H:%M:%S")

原因说明

Discord接口返回的消息创建时间默认是UTC标准时间,假设你所在时区是UTC+7,那UTC的00点对应你本地的07点,直接格式化自然会显示00小时。转成本地时区后,就能得到你预期的正确小时数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 04:30:07