Search code examples
pythonpython-3.xdatetimediscord.pypython-datetime

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


how can I check if a created server invite is below 10 minutes? I tried to make a list that prints every invite that's created below 10 minutes ago, but it doesn't print anything.

I tried:

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

I added:

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

and that was the results from the prints (fresh created invite):

1619006499.447825
1619013699.5136192
7200.065812826157

Solution

  • The 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() to get the current time as a datetime.datetime object.

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

    Alternatively, you could use datetime.timedelta() to compare the differences in time.

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