diff options
| author | Rapptz <[email protected]> | 2021-06-28 01:30:56 -0400 |
|---|---|---|
| committer | Rapptz <[email protected]> | 2021-06-28 01:31:14 -0400 |
| commit | d1a2ee46209917000e57612c0bdce29b5035e15a (patch) | |
| tree | 0cb0cd87fe9a42bcfe10c20e851fcc576339b3eb /discord/utils.py | |
| parent | Fix Guild.vanity_invite causing an error when guild has it unset (diff) | |
| download | discord.py-d1a2ee46209917000e57612c0bdce29b5035e15a.tar.xz discord.py-d1a2ee46209917000e57612c0bdce29b5035e15a.zip | |
Add discord.utils.format_dt helper function
Diffstat (limited to 'discord/utils.py')
| -rw-r--r-- | discord/utils.py | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/discord/utils.py b/discord/utils.py index ccecfeed..7c088b4f 100644 --- a/discord/utils.py +++ b/discord/utils.py @@ -944,3 +944,49 @@ def resolve_annotation( if cache is None: cache = {} return evaluate_annotation(annotation, globalns, locals, cache) + + +TimestampStyle = Literal['f', 'F', 'd', 'D', 't', 'T', 'R'] + + +def format_dt(dt: datetime.datetime, /, style: Optional[TimestampStyle] = None) -> str: + """A helper function to format a :class:`datetime.datetime` for presentation within Discord. + + This allows for a locale-independent way of presenting data using Discord specific Markdown. + + +-------------+----------------------------+-----------------+ + | Style | Example Output | Description | + +=============+============================+=================+ + | t | 22:57 | Short Time | + +-------------+----------------------------+-----------------+ + | T | 22:57:58 | Long Time | + +-------------+----------------------------+-----------------+ + | d | 17/05/2016 | Short Date | + +-------------+----------------------------+-----------------+ + | D | 17 May 2016 | Long Date | + +-------------+----------------------------+-----------------+ + | f (default) | 17 May 2016 22:57 | Short Date Time | + +-------------+----------------------------+-----------------+ + | F | Tuesday, 17 May 2016 22:57 | Long Date Time | + +-------------+----------------------------+-----------------+ + | R | 5 years ago | Relative Time | + +-------------+----------------------------+-----------------+ + + Note that the exact output depends on the user's locale setting in the client. The example output + presented is using the ``en-GB`` locale. + + Parameters + ----------- + dt: :class:`datetime.datetime` + The datetime to format. + style: :class:`str` + The style to format the datetime with. + + Returns + -------- + :class:`str` + The formatted string. + """ + if style is None: + return f'<t:{int(dt.timestamp())}>' + return f'<t:{int(dt.timestamp())}:{style}>' |