2020-03-05 22:51:21 +00:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
"""Custom input type parser."""
|
|
|
|
|
2020-03-15 13:50:58 +00:00
|
|
|
from argparse import ArgumentTypeError
|
2020-03-05 22:51:21 +00:00
|
|
|
|
2020-03-15 13:50:58 +00:00
|
|
|
import dateparser
|
2020-03-05 22:51:21 +00:00
|
|
|
import environs
|
|
|
|
|
|
|
|
env = environs.Env()
|
|
|
|
|
|
|
|
|
|
|
|
def timedelta_validator(value):
|
2023-02-12 13:46:35 +00:00
|
|
|
"""
|
|
|
|
Return the dateparser string for a time in the past.
|
2020-03-05 22:51:21 +00:00
|
|
|
|
|
|
|
:param value: a string containing a time format supported by
|
2020-03-15 13:50:58 +00:00
|
|
|
mod:`dateparser`
|
2020-03-05 22:51:21 +00:00
|
|
|
"""
|
|
|
|
if value is None:
|
|
|
|
return None
|
|
|
|
|
2020-03-15 13:50:58 +00:00
|
|
|
if not dateparser.parse(value):
|
2023-02-12 13:46:35 +00:00
|
|
|
raise ArgumentTypeError(f"'{value}' is not a valid timedelta string")
|
2020-03-15 13:50:58 +00:00
|
|
|
|
|
|
|
return value
|
2020-03-05 22:51:21 +00:00
|
|
|
|
|
|
|
|
2020-03-09 00:05:17 +00:00
|
|
|
def timedelta(value, dt_format=None):
|
2023-02-12 13:46:35 +00:00
|
|
|
"""
|
|
|
|
Return the :class:`datetime.datetime.DateTime` for a time in the past.
|
2020-03-05 22:51:21 +00:00
|
|
|
|
|
|
|
:param value: a string containing a time format supported by
|
2020-03-15 13:50:58 +00:00
|
|
|
mod:`dateparser`
|
2020-03-05 22:51:21 +00:00
|
|
|
"""
|
|
|
|
if value is None:
|
|
|
|
return None
|
2020-03-09 00:05:17 +00:00
|
|
|
|
2020-03-15 13:50:58 +00:00
|
|
|
timedelta = dateparser.parse(
|
|
|
|
value, settings={
|
|
|
|
"TO_TIMEZONE": "UTC",
|
|
|
|
"RETURN_AS_TIMEZONE_AWARE": True
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2020-03-09 00:05:17 +00:00
|
|
|
if dt_format:
|
|
|
|
timedelta = timedelta.strftime(dt_format)
|
|
|
|
|
2023-02-12 13:46:35 +00:00
|
|
|
return timedelta # noqa
|
2020-03-05 22:51:21 +00:00
|
|
|
|
|
|
|
|
|
|
|
@env.parser_for("timedelta_validator")
|
|
|
|
def timedelta_parser(value):
|
|
|
|
try:
|
|
|
|
timedelta_validator(value)
|
|
|
|
return value
|
2020-03-22 16:20:24 +00:00
|
|
|
except ArgumentTypeError as e:
|
2023-02-12 13:46:35 +00:00
|
|
|
raise environs.EnvError(e) from e
|