SpaceTurtle0
SpaceTurtle0

Reputation: 161

How would I get the current time (Not 24 hours) using datetime in discord.py?

So I'm trying to use the timestamp function to just display the time someone edited their message. Currently, this is my code:

@commands.Cog.listener()
async def on_message_edit(self, before, after):
 if before.author != self.bot.user:
  embed=discord.Embed(title="{}".format(before.author), description="Editted a Message:",color=0xfcca03)
  embed.add_field(name= "**Before:** " ,value=before.content, inline=False)
  embed.add_field(name= "**After:** ",value=after.content, inline=False)
  embed.add_field(name="**Details:** ", value = "Channel: " + str(after.channel) + "\n" + "ID: " + str({before.author.id}))
  guild = self.bot.get_guild(357331299792584707)
  embed.set_thumbnail(url = guild.icon_url)
  timestamp = datetime.now() 
  embed.set_footer(text=guild.name + "Timestamp: " + str(timestamp))
  channel = self.bot.get_channel(722949984227688519)
  await channel.send(embed=embed)

The code works but the timestamp is full of other information I don't need.

Example: Timestamp: 2020-11-13 17:48:24.876424

How would I make it so it looks something like this? "Timestamp: 7:43 PM"

Any help would greatly help, thank you!

Upvotes: 0

Views: 6646

Answers (2)

Halmon
Halmon

Reputation: 1077

Instead of simply converting the datetime to str, look into strftime() to format the string you want. In your case you would want to use the %I:%M %p

Upvotes: 0

azro
azro

Reputation: 54148

You may use datetime.strptime

timestamp = datetime.now()
print(timestamp)                        # 2020-11-13 19:12:26.718388
print(timestamp.strftime(r"%I:%M %p"))  # 07:12 PM

Specifically with the following format codes

  • %I for Hour (12-hour clock) as a zero-padded decimal number

  • %p for Locale’s equivalent of either AM or PM

  • %M for Minute as a zero-padded decimal number

Upvotes: 5

Related Questions