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

如何让24小时运行的Discord Bot状态显示美国东部时间的当前日期时间?

Discord Bot状态实时显示美国东部时间解决方案

核心问题分析

你之前的代码仅获取了UTC时间的小时分钟,且只在Bot启动时设置一次状态,不会实时更新,也没有转换到美国东部时区(包含夏令时处理)。要实现目标需要两步:时区转换 + 定时刷新状态。

实现步骤

1. 时区处理(二选一)

  • 若使用Python 3.9+,直接用内置的zoneinfo模块,无需额外安装
  • 低版本Python可安装pytz:pip install pytz

2. 定时更新Bot状态

使用discord.ext.tasks创建循环任务,每隔一段时间刷新状态(建议1分钟,避免频繁请求)。

完整代码示例

import discord
from discord.ext import commands, tasks
from datetime import datetime
# Python3.9+用这个
from zoneinfo import ZoneInfo
# 低版本用pytz的话替换成:
# import pytz

bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())

def get_est_time():
    # 时区转换:美国东部时区(自动处理夏令时)
    # zoneinfo写法
    est_now = datetime.now(tz=ZoneInfo("America/New_York"))
    # pytz写法替换成:
    # est_now = datetime.now(pytz.timezone("America/New_York"))
    # 按照要求的格式输出:MM/DD/YY, HH:MM AM/PM
    return est_now.strftime("%m/%d/%y, %I:%M %p")

@tasks.loop(minutes=1)
async def update_status():
    if bot.user:
        await bot.change_presence(activity=discord.Game(name=get_est_time()))

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user}")
    # 启动定时任务
    update_status.start()

bot.run("你的Bot令牌")

关键说明

  • America/New_York时区会自动处理夏令时(EDT/EST切换),无需手动调整
  • 循环任务设为1分钟刷新一次,平衡实时性和API调用频率
  • %I是12小时制的小时,%p会自动显示AM/PM,完全匹配你要的格式示例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 11:45:29