Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/util/time.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 # Python port of the ms.js node module this is not a direct port some things are
6 # more complicated or less precise and we lean on time delta here.
7
8
9 import datetime
10 import re
11
12 PATTERN = re.compile(r"((?:\d+)?\.?\d+) *([a-z]+)")
13
14
15 def seconds(value):
16 return datetime.timedelta(seconds=int(value))
17
18
19 def minutes(value):
20 return datetime.timedelta(minutes=int(value))
21
22
23 def hours(value):
24 return datetime.timedelta(hours=int(value))
25
26
27 def days(value):
28 return datetime.timedelta(days=int(value))
29
30
31 def months(value):
32 # See warning in years(), below
33 return datetime.timedelta(days=int(value) * 30)
34
35
36 def years(value):
37 # Warning here "years" are vague don't use this for really sensitive date
38 # computation the idea is to give you a absolute amount of time in the
39 # future which is not the same thing as "precisely on this date next year"
40 return datetime.timedelta(days=int(value) * 365)
41
42
43 ALIASES = {}
44 ALIASES["seconds"] = ALIASES["second"] = ALIASES["s"] = seconds
45 ALIASES["minutes"] = ALIASES["minute"] = ALIASES["min"] = minutes
46 ALIASES["hours"] = ALIASES["hour"] = ALIASES["h"] = hours
47 ALIASES["days"] = ALIASES["day"] = ALIASES["d"] = days
48 ALIASES["months"] = ALIASES["month"] = ALIASES["mo"] = months
49 ALIASES["years"] = ALIASES["year"] = ALIASES["y"] = years
50
51
52 class InvalidString(Exception):
53 pass
54
55
56 class UnknownTimeMeasurement(Exception):
57 pass
58
59
60 def value_of(input_str):
61 """
62 Convert a string to a json date in the future
63 :param str input_str: (ex: 1d, 2d, 6years, 2 seconds)
64 :returns: Unit given in seconds
65 """
66
67 matches = PATTERN.search(input_str)
68
69 if matches is None or len(matches.groups()) < 2:
70 raise InvalidString(f"'{input_str}' is invalid string")
71
72 value, unit = matches.groups()
73
74 if unit not in ALIASES:
75 raise UnknownTimeMeasurement(
76 f"{unit} is not a valid time measure use one of {sorted(ALIASES.keys())}"
77 )
78
79 return ALIASES[unit](value)
80
81
82 def json_time_from_now(input_str, now=None, datetime_format=False):
83 """
84 :param str input_str: Input string (see value of)
85 :param datetime now: Optionally set the definition of `now`
86 :param boolean datetime_format: Set `True` to get a `datetime` output
87 :returns: JSON string representation of time in future.
88 """
89
90 if now is None:
91 now = datetime.datetime.now(datetime.timezone.utc)
92
93 time = now + value_of(input_str)
94
95 if datetime_format is True:
96 return time
97 else:
98 # Sorta a big hack but the json schema validator for date does not like the
99 # ISO dates until 'Z' (for timezone) is added...
100 # Microseconds are excluded (see bug 1381801)
101 return time.replace(tzinfo=None).isoformat(timespec="milliseconds") + "Z"
102
103
104 def current_json_time(datetime_format=False):
105 """
106 :param boolean datetime_format: Set `True` to get a `datetime` output
107 :returns: JSON string representation of the current time.
108 """
109 now = datetime.datetime.now(datetime.timezone.utc)
110 if datetime_format is True:
111 return now
112 else:
113 # Microseconds are excluded (see bug 1381801)
114 return now.replace(tzinfo=None).isoformat(timespec="milliseconds") + "Z"