comparison libervia/backend/tools/common/date_utils.py @ 4270:0d7bb4df2343

Reformatted code base using black.
author Goffi <goffi@goffi.org>
date Wed, 19 Jun 2024 18:44:57 +0200
parents c6d85c31a59f
children
comparison
equal deleted inserted replaced
4269:64a85ce8be70 4270:0d7bb4df2343
39 r"\s*(?P<in>\bin\b)?" 39 r"\s*(?P<in>\bin\b)?"
40 r"(?P<date>[^+-][^+]+[^\s+-])?\s*(?P<direction>[-+])?\s*" 40 r"(?P<date>[^+-][^+]+[^\s+-])?\s*(?P<direction>[-+])?\s*"
41 r"\s*(?P<quantity>\d+)\s*" 41 r"\s*(?P<quantity>\d+)\s*"
42 r"(?P<unit>(second|sec|s|minute|min|month|mo|m|hour|hr|h|day|d|week|w|year|yr|y))s?" 42 r"(?P<unit>(second|sec|s|minute|min|month|mo|m|hour|hr|h|day|d|week|w|year|yr|y))s?"
43 r"(?P<ago>\s+ago)?\s*", 43 r"(?P<ago>\s+ago)?\s*",
44 re.I 44 re.I,
45 ) 45 )
46 TIME_SYMBOL_MAP = { 46 TIME_SYMBOL_MAP = {
47 "s": "second", 47 "s": "second",
48 "sec": "second", 48 "sec": "second",
49 "m": "minute", 49 "m": "minute",
70 """ 70 """
71 value = str(value).strip() 71 value = str(value).strip()
72 dayfirst = False if YEAR_FIRST_RE.match(value) else True 72 dayfirst = False if YEAR_FIRST_RE.match(value) else True
73 73
74 try: 74 try:
75 dt = default_tzinfo( 75 dt = default_tzinfo(parser.parse(value, dayfirst=dayfirst), default_tz)
76 parser.parse(value, dayfirst=dayfirst),
77 default_tz)
78 except ParserError as e: 76 except ParserError as e:
79 if value == "now": 77 if value == "now":
80 dt = datetime.datetime.now(tz.tzutc()) 78 dt = datetime.datetime.now(tz.tzutc())
81 else: 79 else:
82 try: 80 try:
84 return int(value) 82 return int(value)
85 except ValueError: 83 except ValueError:
86 raise e 84 raise e
87 return calendar.timegm(dt.utctimetuple()) 85 return calendar.timegm(dt.utctimetuple())
88 86
89 def date_parse_ext(value: str, default_tz: datetime.tzinfo=TZ_UTC) -> float: 87
88 def date_parse_ext(value: str, default_tz: datetime.tzinfo = TZ_UTC) -> float:
90 """Extended date parse which accept relative date 89 """Extended date parse which accept relative date
91 90
92 @param value: date to parse, in any format supported by parser 91 @param value: date to parse, in any format supported by parser
93 and with the hability to specify X days/weeks/months/years in the past or future. 92 and with the hability to specify X days/weeks/months/years in the past or future.
94 Relative date are specified either with something like `[main_date] +1 week` 93 Relative date are specified either with something like `[main_date] +1 week`
101 m = RELATIVE_RE.match(value) 100 m = RELATIVE_RE.match(value)
102 if m is None: 101 if m is None:
103 return date_parse(value, default_tz=default_tz) 102 return date_parse(value, default_tz=default_tz)
104 103
105 if sum(1 for g in ("direction", "in", "ago") if m.group(g)) > 1: 104 if sum(1 for g in ("direction", "in", "ago") if m.group(g)) > 1:
106 raise ValueError( 105 raise ValueError(_('You can use only one of direction (+ or -), "in" and "ago"'))
107 _('You can use only one of direction (+ or -), "in" and "ago"')) 106
108 107 if m.group("direction") == "-" or m.group("ago"):
109 if m.group("direction") == '-' or m.group("ago"):
110 direction = -1 108 direction = -1
111 else: 109 else:
112 direction = 1 110 direction = 1
113 111
114 date = m.group("date") 112 date = m.group("date")
144 date_only: bool = False, 142 date_only: bool = False,
145 auto_limit: int = 7, 143 auto_limit: int = 7,
146 auto_old_fmt: str = "short", 144 auto_old_fmt: str = "short",
147 auto_new_fmt: str = "relative", 145 auto_new_fmt: str = "relative",
148 locale_str: str = C.DEFAULT_LOCALE, 146 locale_str: str = C.DEFAULT_LOCALE,
149 tz_info: Union[datetime.tzinfo, str] = TZ_UTC 147 tz_info: Union[datetime.tzinfo, str] = TZ_UTC,
150 ) -> str: 148 ) -> str:
151 """Format date according to locale 149 """Format date according to locale
152 150
153 @param timestamp: unix time 151 @param timestamp: unix time
154 @param fmt: one of: 152 @param fmt: one of:
184 fmt, auto_limit, auto_old_fmt, auto_new_fmt = "auto", 0, "short", "HH:mm" 182 fmt, auto_limit, auto_old_fmt, auto_new_fmt = "auto", 0, "short", "HH:mm"
185 if fmt == "auto": 183 if fmt == "auto":
186 if auto_limit == 0: 184 if auto_limit == 0:
187 now = datetime.datetime.now(tz_info) 185 now = datetime.datetime.now(tz_info)
188 # we want to use given tz_info, so we don't use date() or today() 186 # we want to use given tz_info, so we don't use date() or today()
189 today = datetime.datetime(year=now.year, month=now.month, day=now.day, 187 today = datetime.datetime(
190 tzinfo=now.tzinfo) 188 year=now.year, month=now.month, day=now.day, tzinfo=now.tzinfo
189 )
191 today = calendar.timegm(today.utctimetuple()) 190 today = calendar.timegm(today.utctimetuple())
192 if timestamp < today: 191 if timestamp < today:
193 fmt = auto_old_fmt 192 fmt = auto_old_fmt
194 else: 193 else:
195 fmt = auto_new_fmt 194 fmt = auto_new_fmt
208 elif fmt in ("short", "long", "full"): 207 elif fmt in ("short", "long", "full"):
209 if date_only: 208 if date_only:
210 dt = datetime.datetime.fromtimestamp(timestamp, tz_info) 209 dt = datetime.datetime.fromtimestamp(timestamp, tz_info)
211 return dates.format_date(dt, format=fmt, locale=locale_str) 210 return dates.format_date(dt, format=fmt, locale=locale_str)
212 else: 211 else:
213 return dates.format_datetime(timestamp, format=fmt, locale=locale_str, 212 return dates.format_datetime(
214 tzinfo=tz_info) 213 timestamp, format=fmt, locale=locale_str, tzinfo=tz_info
214 )
215 elif fmt == "iso": 215 elif fmt == "iso":
216 if date_only: 216 if date_only:
217 fmt = "yyyy-MM-dd" 217 fmt = "yyyy-MM-dd"
218 else: 218 else:
219 fmt = "yyyy-MM-ddTHH:mm:ss'Z'" 219 fmt = "yyyy-MM-ddTHH:mm:ss'Z'"
220 return dates.format_datetime(timestamp, format=fmt) 220 return dates.format_datetime(timestamp, format=fmt)
221 else: 221 else:
222 return dates.format_datetime(timestamp, format=fmt, locale=locale_str, 222 return dates.format_datetime(
223 tzinfo=tz_info) 223 timestamp, format=fmt, locale=locale_str, tzinfo=tz_info
224 )
224 225
225 226
226 def delta2human(start_ts: Union[float, int], end_ts: Union[float, int]) -> str: 227 def delta2human(start_ts: Union[float, int], end_ts: Union[float, int]) -> str:
227 """Convert delta of 2 unix times to human readable text 228 """Convert delta of 2 unix times to human readable text
228 229
232 if end_ts < start_ts: 233 if end_ts < start_ts:
233 raise exceptions.InternalError( 234 raise exceptions.InternalError(
234 "end timestamp must be bigger or equal to start timestamp !" 235 "end timestamp must be bigger or equal to start timestamp !"
235 ) 236 )
236 rd = relativedelta( 237 rd = relativedelta(
237 datetime.datetime.fromtimestamp(end_ts), 238 datetime.datetime.fromtimestamp(end_ts), datetime.datetime.fromtimestamp(start_ts)
238 datetime.datetime.fromtimestamp(start_ts)
239 ) 239 )
240 text_elems = [] 240 text_elems = []
241 for unit in ("years", "months", "days", "hours", "minutes"): 241 for unit in ("years", "months", "days", "hours", "minutes"):
242 value = getattr(rd, unit) 242 value = getattr(rd, unit)
243 if value == 1: 243 if value == 1: