簡體   English   中英

使用“幾天前”而不是日期

[英]Use "days ago" instead of date

我目前正在開發一個 discord 機器人,它向我顯示 ID、姓名等用戶信息,我添加了一個加入日期和一個帳戶創建日期,它們工作正常,但我也想包括一個“幾天前”而不是空白日期。

這是我的代碼:

from unicodedata import name
import discord
from datetime import datetime
from discord.ext import commands

intents = discord.Intents.all()
bot = commands.Bot(command_prefix='.',intents=intents)

@bot.event
async def on_ready():
    print("Ready!")

@bot.command(name="user")
async def user(ctx,user:discord.Member=None):

    if user==None:
        user=ctx.author

    rlist = []
    for role in user.roles:
        if role.name != "@everyone":
            rlist.append(role.mention)
    b = ','.join(rlist)
    
    if rlist:
        b = ','.join(rlist)
    else:
        b = "No roles"


    embed = discord.Embed(colour=user.color,timestamp=ctx.message.created_at)

    embed.set_author(name=f"User Info - {user}"),
    embed.set_thumbnail(url=user.avatar.url),
    embed.set_footer(text=f'Requested by - {ctx.author}',
    icon_url=ctx.author.avatar.url)

    embed.add_field(name='ID:' ,value=user.id,inline=False)
    embed.add_field(name='Name:' ,value=user.display_name,inline=False)

    embed.add_field(name='Created at:' ,value=datetime.strftime(user.created_at, "%#d/%m/%Y"), inline=False)
    embed.add_field(name='Joined at:' ,value=datetime.strftime(user.joined_at, "%#d/%m/%Y"), inline=False)
    
    embed.add_field(name='Bot?' ,value=user.bot,inline=False)

    embed.add_field(name=f'Roles:({len(rlist)})',value=''.join([b]),inline=False)
    embed.add_field(name='Top Role:' ,value=user.top_role.mention,inline=False)

    await ctx.send(embed=embed)

我已經試過了

    duration = dt.datetime.now() - user.joined_at 

    hours, remainder = divmod(int(duration .total_seconds()), 3600)
    minutes, seconds = divmod(remainder, 60)
    days, hours = divmod(hours, 24)

    await ctx.send(f"Joined before {days}d, {hours}h, {minutes}m, {seconds}s")

這個不起作用,我認為它與時區有關,我試圖消除時區意識,但這對我也不起作用。

你可以這樣做:

joined_at = user.joined_at.timestamp()
delta = int(datetime.utcnow().timestamp()) - int(joined_at)
hours, remainder = divmod(delta, 3600)
minutes, seconds = divmod(remainder, 60)
days, hours = divmod(hours, 24)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM