Search code examples
pythondiscord.pyunix-timestamp

adding any unix timestamp in discord.py


i want to add unix timestamp in the giveaway time like in this image

here is the code:

@client.command()
async def giveaway(ctx, days:int, hours:int, minutes:int, seconds:int, prize:str):
  time = days + hours + minutes + seconds
  embed = discord.Embed(title=prize, description=f"time: <t:{time}:R>")
  await ctx.send(embed=embed, delete_after=time)
  endembed = discord.Embed(title=f"you have won {prize}", description="The time has ended")
  await ctx.send(embed=endembed)

when I run the code it shows me this image


Solution

  • You can do this by using the mktime function in the time module.

    import datetime
    import time
    
    def convert_to_unix_time(date: datetime.datetime, days: int, hours: int, minutes: int, seconds: int) -> str:
        # Get the end date
        end_date = date + datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
    
        # Get a tuple of the date attributes
        date_tuple = (end_date.year, end_date.month, end_date.day, end_date.hour, end_date.minute, end_date.second)
    
        # Convert to unix time
        return f'<t:{int(time.mktime(datetime.datetime(*date_tuple).timetuple()))}:R>'
    

    The returned value should like somewhat like this: <t:1655392367:R>

    Pasting the returned string will give a dynamic display as shown in the image you have provided.

    The mktime function returns a float value. For the datetime to be displayed dynamically, the value in between must be numbers only.

    The R in the end of the returned string stands for relative. The dynamic display will be relative to current time. The other formats are t, T, d, D, f and F.