aboutsummaryrefslogtreecommitdiffstats
path: root/bot/converters.py
diff options
context:
space:
mode:
Diffstat (limited to 'bot/converters.py')
-rw-r--r--bot/converters.py33
1 files changed, 33 insertions, 0 deletions
diff --git a/bot/converters.py b/bot/converters.py
index 339da7b60..49ac488f4 100644
--- a/bot/converters.py
+++ b/bot/converters.py
@@ -4,6 +4,7 @@ from datetime import datetime
from ssl import CertificateError
from typing import Union
+import dateutil.parser
import discord
from aiohttp import ClientConnectorError
from dateutil.relativedelta import relativedelta
@@ -215,3 +216,35 @@ class Duration(Converter):
now = datetime.utcnow()
return now + delta
+
+
+class ISODateTime(Converter):
+ """"Converts an ISO-8601 datetime string into a datetime.datetime."""
+
+ async def convert(self, ctx: Context, datetime_string: str) -> datetime:
+ """
+ Converts a ISO-8601 `datetime_string` into a `datetime.datetime` object.
+
+ The converter is flexible in the formats it accepts, as it uses the `isoparse` method of
+ `dateutil.parser`. In general, it accepts datetime strings that start with a date,
+ optionally followed by a time.
+
+ See: <https://dateutil.readthedocs.io/en/stable/parser.html#dateutil.parser.isoparse>
+
+ Formats that are guaranteed to be valid by our tests are:
+
+ - `YYYY-mm-ddTHH:MM:SS` | `YYYY-mm-dd HH:MM:SS`
+ - `YYYY-mm-ddTHH:MM` | `YYYY-mm-dd HH:MM`
+ - `YYYY-mm-dd`
+ - `YYYY-mm`
+ - `YYYY`
+
+ Note: ISO-8601 specifies a `T` as the separator between the date and the time part of the
+ datetime string. The converter accepts both a `T` and a single space character.
+ """
+ try:
+ dt = dateutil.parser.isoparse(datetime_string)
+ except ValueError:
+ raise BadArgument(f"`{datetime_string}` is not a valid ISO-8601 datetime string")
+
+ return dt