changeset 3599:ab1fe6b25631

tools (common/date_utils): accept more units (shortcuts) + fix timezone when date with relative delta is used
author Goffi <goffi@goffi.org>
date Thu, 29 Jul 2021 22:51:01 +0200
parents d390ff50af0f
children 1709f0a78f50
files sat/tools/common/date_utils.py
diffstat 1 files changed, 22 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- a/sat/tools/common/date_utils.py	Thu Jul 29 22:51:01 2021 +0200
+++ b/sat/tools/common/date_utils.py	Thu Jul 29 22:51:01 2021 +0200
@@ -31,8 +31,22 @@
 import re
 
 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)
+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]+")
 TZ_UTC = tz.tzutc()
 TZ_LOCAL = tz.gettz()
@@ -84,11 +98,15 @@
     if not date or date == "now":
         dt = datetime.datetime.now(tz.tzutc())
     else:
-        dt = default_tzinfo(parser.parse(date, dayfirst=True))
+        dt = default_tzinfo(parser.parse(date, dayfirst=True), default_tz)
 
     quantity = int(m.group("quantity"))
-    key = m.group("unit").lower() + "s"
-    delta_kw = {key: direction * quantity}
+    unit = m.group("unit").lower()
+    try:
+        unit = TIME_SYMBOL_MAP[unit]
+    except KeyError:
+        pass
+    delta_kw = {f"{unit}s": direction * quantity}
     dt = dt + relativedelta(**delta_kw)
     return calendar.timegm(dt.utctimetuple())