comparison sat/tools/common/date_utils.py @ 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 b258dce27d6d
children bef32f3ccc06
comparison
equal deleted inserted replaced
3598:d390ff50af0f 3599:ab1fe6b25631
29 import calendar 29 import calendar
30 import time 30 import time
31 import re 31 import re
32 32
33 RELATIVE_RE = re.compile(r"(?P<date>.*?)(?P<direction>[-+]?) *(?P<quantity>\d+) *" 33 RELATIVE_RE = re.compile(r"(?P<date>.*?)(?P<direction>[-+]?) *(?P<quantity>\d+) *"
34 r"(?P<unit>(second|minute|hour|day|week|month|year))s?" 34 r"(?P<unit>(second|sec|s|minute|min|month|mo|m|hour|hr|h|day|d"
35 r"|week|w|year|yr|y))s?"
35 r"(?P<ago> +ago)?", re.I) 36 r"(?P<ago> +ago)?", re.I)
37 TIME_SYMBOL_MAP = {
38 "s": "second",
39 "sec": "second",
40 "m": "minute",
41 "min": "minute",
42 "h": "hour",
43 "hr": "hour",
44 "d": "day",
45 "w": "week",
46 "mo": "month",
47 "y": "year",
48 "yr": "year",
49 }
36 YEAR_FIRST_RE = re.compile(r"\d{4}[^\d]+") 50 YEAR_FIRST_RE = re.compile(r"\d{4}[^\d]+")
37 TZ_UTC = tz.tzutc() 51 TZ_UTC = tz.tzutc()
38 TZ_LOCAL = tz.gettz() 52 TZ_LOCAL = tz.gettz()
39 # used to replace values when something is missing 53 # used to replace values when something is missing
40 DEFAULT_DATETIME = datetime.datetime(2000, 0o1, 0o1) 54 DEFAULT_DATETIME = datetime.datetime(2000, 0o1, 0o1)
82 96
83 date = m.group("date").strip().lower() 97 date = m.group("date").strip().lower()
84 if not date or date == "now": 98 if not date or date == "now":
85 dt = datetime.datetime.now(tz.tzutc()) 99 dt = datetime.datetime.now(tz.tzutc())
86 else: 100 else:
87 dt = default_tzinfo(parser.parse(date, dayfirst=True)) 101 dt = default_tzinfo(parser.parse(date, dayfirst=True), default_tz)
88 102
89 quantity = int(m.group("quantity")) 103 quantity = int(m.group("quantity"))
90 key = m.group("unit").lower() + "s" 104 unit = m.group("unit").lower()
91 delta_kw = {key: direction * quantity} 105 try:
106 unit = TIME_SYMBOL_MAP[unit]
107 except KeyError:
108 pass
109 delta_kw = {f"{unit}s": direction * quantity}
92 dt = dt + relativedelta(**delta_kw) 110 dt = dt + relativedelta(**delta_kw)
93 return calendar.timegm(dt.utctimetuple()) 111 return calendar.timegm(dt.utctimetuple())
94 112
95 113
96 def date_fmt(timestamp, fmt="short", date_only=False, auto_limit=7, auto_old_fmt="short", 114 def date_fmt(timestamp, fmt="short", date_only=False, auto_limit=7, auto_old_fmt="short",