tools (common/date_utils): accept more units (shortcuts) + fix timezone when date with relative delta is used
This commit is contained in:
parent
35bfb8b8b7
commit
aab8a38836
1 changed files with 22 additions and 4 deletions
|
|
@ -31,8 +31,22 @@ import time
|
||||||
import re
|
import re
|
||||||
|
|
||||||
RELATIVE_RE = re.compile(r"(?P<date>.*?)(?P<direction>[-+]?) *(?P<quantity>\d+) *"
|
RELATIVE_RE = re.compile(r"(?P<date>.*?)(?P<direction>[-+]?) *(?P<quantity>\d+) *"
|
||||||
r"(?P<unit>(second|minute|hour|day|week|month|year))s?"
|
r"(?P<unit>(second|sec|s|minute|min|month|mo|m|hour|hr|h|day|d"
|
||||||
|
r"|week|w|year|yr|y))s?"
|
||||||
r"(?P<ago> +ago)?", re.I)
|
r"(?P<ago> +ago)?", re.I)
|
||||||
|
TIME_SYMBOL_MAP = {
|
||||||
|
"s": "second",
|
||||||
|
"sec": "second",
|
||||||
|
"m": "minute",
|
||||||
|
"min": "minute",
|
||||||
|
"h": "hour",
|
||||||
|
"hr": "hour",
|
||||||
|
"d": "day",
|
||||||
|
"w": "week",
|
||||||
|
"mo": "month",
|
||||||
|
"y": "year",
|
||||||
|
"yr": "year",
|
||||||
|
}
|
||||||
YEAR_FIRST_RE = re.compile(r"\d{4}[^\d]+")
|
YEAR_FIRST_RE = re.compile(r"\d{4}[^\d]+")
|
||||||
TZ_UTC = tz.tzutc()
|
TZ_UTC = tz.tzutc()
|
||||||
TZ_LOCAL = tz.gettz()
|
TZ_LOCAL = tz.gettz()
|
||||||
|
|
@ -84,11 +98,15 @@ def date_parse_ext(value, default_tz=TZ_UTC):
|
||||||
if not date or date == "now":
|
if not date or date == "now":
|
||||||
dt = datetime.datetime.now(tz.tzutc())
|
dt = datetime.datetime.now(tz.tzutc())
|
||||||
else:
|
else:
|
||||||
dt = default_tzinfo(parser.parse(date, dayfirst=True))
|
dt = default_tzinfo(parser.parse(date, dayfirst=True), default_tz)
|
||||||
|
|
||||||
quantity = int(m.group("quantity"))
|
quantity = int(m.group("quantity"))
|
||||||
key = m.group("unit").lower() + "s"
|
unit = m.group("unit").lower()
|
||||||
delta_kw = {key: direction * quantity}
|
try:
|
||||||
|
unit = TIME_SYMBOL_MAP[unit]
|
||||||
|
except KeyError:
|
||||||
|
pass
|
||||||
|
delta_kw = {f"{unit}s": direction * quantity}
|
||||||
dt = dt + relativedelta(**delta_kw)
|
dt = dt + relativedelta(**delta_kw)
|
||||||
return calendar.timegm(dt.utctimetuple())
|
return calendar.timegm(dt.utctimetuple())
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue