Debian Codegraph @

cylc/flow/wallclock.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 """Wall clock related utilities."""
17
18 from calendar import timegm
19 from datetime import datetime, timedelta, timezone
20 from typing import Dict, Optional
21
22 from metomi.isodatetime.timezone import (
23 get_local_time_zone_format, get_local_time_zone, TimeZoneFormatMode)
24
25
26 DATE_TIME_FORMAT_BASIC = "%Y%m%dT%H%M%S"
27 DATE_TIME_FORMAT_BASIC_SUB_SECOND = "%Y%m%dT%H%M%S.%f"
28 DATE_TIME_FORMAT_EXTENDED = "%Y-%m-%dT%H:%M:%S"
29 DATE_TIME_FORMAT_EXTENDED_SUB_SECOND = "%Y-%m-%dT%H:%M:%S.%f"
30
31 _FLAGS = {r'utc_mode': False}
32
33 RE_DATE_TIME_FORMAT_EXTENDED = (
34 r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-][\d:]+)?")
35
36 TIME_FORMAT_BASIC = "%H%M%S"
37 TIME_FORMAT_BASIC_SUB_SECOND = "%H%M%S.%f"
38 TIME_FORMAT_EXTENDED = "%H:%M:%S"
39 TIME_FORMAT_EXTENDED_SUB_SECOND = "%H:%M:%S.%f"
40
41 TIME_ZONE_STRING_UTC = "Z"
42 TIME_ZONE_UTC_UTC_OFFSET = (0, 0)
43
44 TIME_ZONE_LOCAL_INFO = {
45 "hours": get_local_time_zone()[0],
46 "minutes": get_local_time_zone()[1],
47 "string_basic": get_local_time_zone_format(
48 TimeZoneFormatMode.reduced),
49 "string_extended": get_local_time_zone_format(
50 TimeZoneFormatMode.extended)
51 }
52
53 TIME_ZONE_UTC_INFO = {
54 "hours": TIME_ZONE_UTC_UTC_OFFSET[0],
55 "minutes": TIME_ZONE_UTC_UTC_OFFSET[1],
56 "string_basic": TIME_ZONE_STRING_UTC,
57 "string_extended": TIME_ZONE_STRING_UTC
58 }
59
60 PARSER = None
61
62
63 def get_utc_mode():
64 """Return value of UTC mode."""
65 return _FLAGS['utc_mode']
66
67
68 def set_utc_mode(mode):
69 """Set value of UTC mode."""
70 _FLAGS['utc_mode'] = bool(mode)
71
72
73 def now(override_use_utc=None):
74 """Return a current-time datetime.datetime and a UTC timezone flag.
75
76 Keyword arguments:
77 override_use_utc (default None) - a boolean (or None) that, if
78 True, gives the date and time in UTC. If False, it gives the date
79 and time in the local time zone. If None, the _FLAGS['utc_mode'] boolean is
80 used.
81
82 """
83 if override_use_utc or (override_use_utc is None and _FLAGS['utc_mode']):
84 return datetime.utcnow(), False
85 else:
86 return datetime.now(), True
87
88
89 def get_current_time_string(display_sub_seconds=False, override_use_utc=None,
90 use_basic_format=False):
91 """Return a string representing the current system time.
92
93 Keyword arguments:
94 display_sub_seconds (default False) - a boolean that, if True,
95 switches on microsecond reporting
96 override_use_utc (default None) - a boolean (or None) that, if
97 True, switches on utc time zone reporting. If False, it switches
98 off utc time zone reporting (even if _FLAGS['utc_mode'] is True). If None,
99 the _FLAGS['utc_mode'] boolean is used.
100 use_basic_format (default False) - a boolean that, if True,
101 represents the date/time without "-" or ":" delimiters. This is
102 most useful for filenames where ":" may cause problems.
103
104 """
105 date_time, date_time_is_local = now(override_use_utc=override_use_utc)
106 return get_time_string(date_time, display_sub_seconds=display_sub_seconds,
107 override_use_utc=override_use_utc,
108 date_time_is_local=date_time_is_local,
109 use_basic_format=use_basic_format)
110
111
112 def get_time_string(
113 date_time: datetime,
114 display_sub_seconds: bool = False,
115 override_use_utc: Optional[bool] = None,
116 use_basic_format: bool = False,
117 date_time_is_local: bool = False,
118 custom_time_zone_info: Optional[Dict] = None,
119 ):
120 """Return a string representing the current system time.
121
122 Args:
123 date_time: Datetime to operate on.
124 display_sub_seconds:
125 Switch on microsecond reporting.
126 override_use_utc:
127 Switch on utc time zone reporting.
128 If False, it switches off utc time zone reporting even
129 if ``_FLAGS['utc_mode']`` is True).
130 If None, the ``_FLAGS['utc_mode']`` boolean is used.
131 use_basic_format:
132 Represent the date/time without "-" or ":"
133 delimiters. This is useful for filenames, where ":" may
134 cause problems.
135 date_time_is_local:
136 Indicates that the date_time argument
137 object is in the local time zone, not UTC.
138 custom_time_zone_info:
139 A dictionary that enforces a particular time zone:
140
141 .. code-block:: python
142 {
143 "hours": _hours, # offset from UTC
144 "minutes": _minutes, # offset from utc
145 "string_basic": _string, # timezone designators
146 "string_extened": _string
147 }
148
149 Usage of ``string_basic`` or ``string_extended`` is
150 switched by ``use_basic_format``.
151
152 """
153 time_zone_string = None
154 local_tz = get_local_time_zone()
155 if custom_time_zone_info is not None:
156 custom_hours = custom_time_zone_info["hours"]
157 custom_minutes = custom_time_zone_info["minutes"]
158 if use_basic_format:
159 custom_string = custom_time_zone_info["string_basic"]
160 else:
161 custom_string = custom_time_zone_info["string_extended"]
162 if date_time_is_local:
163 date_time_hours, date_time_minutes = local_tz
164 else:
165 date_time_hours, date_time_minutes = (0, 0)
166 diff_hours = custom_hours - date_time_hours
167 diff_minutes = custom_minutes - date_time_minutes
168 date_time = date_time + timedelta(
169 hours=diff_hours, minutes=diff_minutes)
170 time_zone_string = custom_string
171 elif override_use_utc or (override_use_utc is None and _FLAGS['utc_mode']):
172 time_zone_string = TIME_ZONE_STRING_UTC
173 if date_time_is_local:
174 date_time = date_time - timedelta(
175 hours=local_tz[0],
176 minutes=local_tz[1]
177 )
178 else:
179 if use_basic_format:
180 time_zone_string = get_local_time_zone_format(
181 TimeZoneFormatMode.reduced)
182 else:
183 time_zone_string = get_local_time_zone_format(
184 TimeZoneFormatMode.extended)
185 if not date_time_is_local:
186 diff_hours, diff_minutes = local_tz
187 date_time = date_time + timedelta(
188 hours=diff_hours, minutes=diff_minutes)
189 if use_basic_format:
190 date_time_format_string = DATE_TIME_FORMAT_BASIC
191 if display_sub_seconds:
192 date_time_format_string = DATE_TIME_FORMAT_BASIC_SUB_SECOND
193 else:
194 date_time_format_string = DATE_TIME_FORMAT_EXTENDED
195 if display_sub_seconds:
196 date_time_format_string = DATE_TIME_FORMAT_EXTENDED_SUB_SECOND
197 date_time_string = date_time.strftime(date_time_format_string)
198 return date_time_string + time_zone_string
199
200
201 def get_time_string_from_unix_time(unix_time, display_sub_seconds=False,
202 use_basic_format=False,
203 custom_time_zone_info=None):
204 """Convert a unix timestamp into a local time zone datetime.datetime.
205
206 Arguments:
207 unix_time - an integer or float number of seconds since the Unix
208 epoch.
209
210 Keyword arguments:
211 display_sub_seconds (default False) - a boolean that, if True,
212 switches on microsecond reporting
213 use_basic_format (default False) - a boolean that, if True,
214 represents the date/time without "-" or ":" delimiters. This is
215 most useful for filenames where ":" may cause problems.
216 custom_time_zone_info (default None) - a dictionary that enforces
217 a particular time zone. It looks like {"hours": _hours,
218 "minutes": _minutes, "string": _string} where _hours and _minutes
219 are the hours and minutes offset from UTC and _string is the string
220 to use as the time zone designator.
221
222 """
223 date_time = datetime.fromtimestamp(unix_time, timezone.utc)
224 return get_time_string(date_time,
225 display_sub_seconds=display_sub_seconds,
226 use_basic_format=use_basic_format,
227 override_use_utc=None,
228 date_time_is_local=False,
229 custom_time_zone_info=custom_time_zone_info)
230
231
232 def get_unix_time_from_time_string(datetime_string):
233 """Convert a datetime string into a unix timestamp.
234
235 The datetime_string must match DATE_TIME_FORMAT_EXTENDED above,
236 which is the extended ISO 8601 year-month-dayThour:minute:second format,
237 plus a valid ISO 8601 time zone. For example, 2016-09-07T11:21:00+01:00,
238 2016-12-25T06:00:00Z, or 2016-12-25T06:00:00+13.
239
240 isodatetime is not used to do the whole parsing, partly for performance,
241 but mostly because the calendar may be in non-Gregorian mode.
242
243 """
244 try:
245 date_time_utc = datetime.strptime(
246 datetime_string, DATE_TIME_FORMAT_EXTENDED + "Z")
247 except ValueError:
248 global PARSER
249 if PARSER is None:
250 from metomi.isodatetime.parsers import TimePointParser
251 PARSER = TimePointParser()
252 time_zone_info = PARSER.get_info(datetime_string)[1]
253 time_zone_hour = int(time_zone_info["time_zone_hour"])
254 time_zone_minute = int(time_zone_info.get("time_zone_minute", 0))
255 offset_seconds = 3600 * time_zone_hour + 60 * time_zone_minute
256 if "+" in datetime_string:
257 datetime_string = datetime_string.split("+")[0]
258 else:
259 datetime_string = datetime_string.rsplit("-", 1)[0]
260 date_time = datetime.strptime(
261 datetime_string, DATE_TIME_FORMAT_EXTENDED)
262 date_time_utc = date_time - timedelta(seconds=offset_seconds)
263 return timegm(date_time_utc.timetuple())
264
265
266 def get_seconds_as_interval_string(seconds):
267 """Convert a number of seconds into an ISO 8601 duration string."""
268 from metomi.isodatetime.data import Duration
269 return str(Duration(seconds=seconds, standardize=True))