Discord py - 如何检查创建日期是否低于 10 分钟?

Discord py - How to check if creating date is below 10 minutes?

如何检查创建的服务器邀请是否少于 10 分钟?我试图制作一个列表,打印 10 分钟前创建的每个邀请,但它没有打印任何东西。

我试过了:

invites = await ctx.guild.invites()
for invite in invites:
    if (time.time() - invite.created_at.timestamp()) < 600:
        print(invite)

我补充道:

@bot.event
async def on_invite_create(invite):
    print(invite.created_at.timestamp())
    print(time.time())
    print(time.time() - invite.created_at.timestamp())

这就是打印的结果(新创建的邀请):

1619006499.447825
1619013699.5136192
7200.065812826157

discord.Guild.invites() method returns a list of discord.Invite objects. Each discord.Invite object has an attribute created_at, which returns the time which the invite was created at as a datetime.datetime object. This is different than time.time(), which is simply a float. So, you should use datetime.datetime.now()获取当前时间作为datetime.datetime对象。

import datetime

invites = await ctx.guild.invites()
for invite in invites:
    if (datetime.datetime.now() - invite.created_at).total_seconds() < 600:
        print(invite)

或者,您可以使用 datetime.timedelta() 来比较时间差异。

for invite in await ctx.guild.invites():
    if datetime.datetime.now() - invite.created_at < datetime.timedelta(minutes=10):
        print(invite)