Debian Codegraph @

metomi/isodatetime/datetimeoper.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # -----------------------------------------------------------------------------
3 # Copyright (C) British Crown (Met Office) & Contributors.
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Lesser General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 # -----------------------------------------------------------------------------
18 """High level common date-time point and duration utilities."""
19
20 from datetime import datetime
21 import os
22 import time
23
24 from .data import (Calendar, TimePoint,
25 get_timepoint_for_now as now2point)
26 from .dumpers import TimePointDumper
27 from .parsers import TimePointParser, DurationParser, TimeRecurrenceParser
28 from metomi.isodatetime.exceptions import OffsetValueError
29
30
31 class DateTimeOperator(object):
32
33 """A class to parse and print date string with an offset."""
34
35 CURRENT_TIME_DUMP_FORMAT = "CCYY-MM-DDThh:mm:ss+hh:mm"
36 CURRENT_TIME_DUMP_FORMAT_Z = "CCYY-MM-DDThh:mm:ssZ"
37
38 ENV_REF = "ISODATETIMEREF"
39 ENV_CALENDAR_MODE = "ISODATETIMECALENDAR"
40
41 # strptime formats and their compatibility with the ISO 8601 parser.
42 PARSE_FORMATS = [
43 "%a %b %d %H:%M:%S %Y", # ctime
44 "%a %d %b %H:%M:%S %Z %Y", # Unix "date"
45 "%Y-%m-%dT%H:%M:%S", # ISO8601, extended
46 "%Y%m%dT%H%M%S", # ISO8601, basic
47 ]
48
49 STR_NOW = "now"
50 STR_REF = "ref"
51
52 UNITS = {
53 "w": "weeks",
54 "d": "days",
55 "h": "hours",
56 "m": "minutes",
57 "s": "seconds",
58 }
59
60 def __init__(
61 self,
62 parse_format=None,
63 utc_mode=False,
64 calendar_mode=None,
65 ref_point_str=None,
66 ):
67 """Constructor.
68
69 parse_format -- If specified, parse with the specified format.
70 Otherwise, parse with one of the format strings in
71 self.PARSE_FORMATS. The format should be a string
72 compatible to strptime(3).
73
74 utc_mode -- If True, parse/print in UTC mode rather than local or
75 other timezones.
76
77 calendar_mode -- Set calendar mode, for isodatetime.data.Calendar.
78
79 ref_point_str -- Set the reference time point for operations.
80 If not specified, operations use current date time.
81
82 """
83 self.custom_parse_format = parse_format
84 self.utc_mode = utc_mode
85 if self.utc_mode:
86 assumed_time_zone = (0, 0)
87 else:
88 assumed_time_zone = None
89
90 if not calendar_mode:
91 calendar_mode = os.getenv(self.ENV_CALENDAR_MODE)
92 self.set_calendar_mode(calendar_mode)
93
94 self.time_point_dumper = TimePointDumper()
95 self.time_point_parser = TimePointParser(
96 assumed_time_zone=assumed_time_zone)
97 self.duration_parser = DurationParser()
98 self.recurrence_parser = TimeRecurrenceParser(
99 self.time_point_parser, self.duration_parser)
100
101 if ref_point_str is None:
102 self.ref_point_str = os.getenv(self.ENV_REF)
103 else:
104 self.ref_point_str = ref_point_str
105
106 def date_format(self, print_format, time_point):
107 """Reformat time_point according to print_format.
108
109 time_point -- The time point to format.
110
111 """
112 if "%" in print_format:
113 return self.strftime(time_point, print_format)
114 return self.time_point_dumper.dump(time_point, print_format)
115
116 def date_parse(self, time_point_str=None):
117 """Parse time_point_str.
118
119 Return (t, format) where t is a isodatetime.data.TimePoint object and
120 format is the format that matches time_point_str.
121
122 time_point_str -- The time point string to parse.
123 Otherwise, use ref time.
124
125 """
126 if time_point_str == self.STR_REF:
127 time_point_str = self.ref_point_str
128 if time_point_str is None or time_point_str == self.STR_NOW:
129 time_point = now2point().to_local_time_zone()
130 if self.utc_mode or time_point.get_time_zone_utc(): # is in UTC
131 parse_format = self.CURRENT_TIME_DUMP_FORMAT_Z
132 else:
133 parse_format = self.CURRENT_TIME_DUMP_FORMAT
134 elif self.custom_parse_format is not None:
135 parse_format = self.custom_parse_format
136 time_point = self.strptime(time_point_str, parse_format)
137 else:
138 time_point = None
139 for parse_format in self.PARSE_FORMATS:
140 try:
141 time_point = self.strptime(time_point_str, parse_format)
142 break
143 except ValueError:
144 pass
145 if time_point is None:
146 time_point = self.time_point_parser.parse(
147 time_point_str,
148 dump_as_parsed=True)
149 parse_format = time_point.dump_format
150 if self.utc_mode:
151 time_point = time_point.to_utc()
152 return time_point, parse_format
153
154 def date_shift(self, time_point, offset=None):
155 """Return a date string with an offset.
156
157 time_point -- A time point or time point string.
158 Otherwise, use current time.
159
160 offset -- If specified, it should be a string containing the offset
161 that has the format "[+/-]nU[nU...]" where "n" is an
162 integer, and U is a unit matching a key in self.UNITS.
163
164 """
165 # Offset
166 if offset:
167 sign = "+"
168 if offset.startswith("-") or offset.startswith("+"):
169 sign = offset[0]
170 offset = offset[1:]
171 # Parse and apply.
172 try:
173 duration = self.duration_parser.parse(offset)
174 except ValueError:
175 raise OffsetValueError(offset)
176 if sign == "-":
177 time_point -= duration
178 else:
179 time_point += duration
180
181 return time_point
182
183 @staticmethod
184 def date_diff(time_point_1=None, time_point_2=None):
185 """Return (duration, is_negative) between two TimePoint objects.
186
187 duration -- is a Duration instance.
188 is_negative -- is "-" if time_point_2 is in the past of time_point_1.
189 """
190 if time_point_2 < time_point_1:
191 return (time_point_1 - time_point_2, "-")
192 else:
193 return (time_point_2 - time_point_1, "")
194
195 @staticmethod
196 def date_diff_format(print_format, duration, sign):
197 """Format a duration."""
198 if print_format:
199 delta_lookup = {
200 "y": duration.years,
201 "m": duration.months,
202 "d": duration.days,
203 "h": duration.hours,
204 "M": duration.minutes,
205 "s": duration.seconds,
206 }
207 expression = ""
208 for item in print_format:
209 if item not in delta_lookup:
210 expression += item
211 elif float(delta_lookup[item]).is_integer():
212 expression += str(int(delta_lookup[item]))
213 else:
214 expression += str(delta_lookup[item])
215 return sign + expression
216 else:
217 return sign + str(duration)
218
219 @staticmethod
220 def get_calendar_mode():
221 """Get current calendar mode."""
222 return Calendar.default().mode
223
224 @staticmethod
225 def set_calendar_mode(calendar_mode):
226 """Set calendar mode for subsequent operations.
227
228 Raise KeyError if calendar_mode is invalid.
229
230 """
231 Calendar.default().set_mode(calendar_mode)
232
233 def strftime(self, time_point, print_format):
234 """Use either the isodatetime or datetime strftime time formatting."""
235 try:
236 return time_point.strftime(print_format)
237 except ValueError:
238 return self.get_datetime_strftime(time_point, print_format)
239
240 def strptime(self, time_point_str, parse_format):
241 """Use either the isodatetime or datetime strptime time parsing."""
242 try:
243 return self.time_point_parser.strptime(
244 time_point_str, parse_format)
245 except ValueError:
246 return self.get_datetime_strptime(time_point_str, parse_format)
247
248 @staticmethod
249 def get_datetime_strftime(time_point, print_format):
250 """Use the datetime library's strftime as a fallback."""
251 calendar_date = time_point.to_calendar_date()
252 year, month, day = calendar_date.get_calendar_date()
253 hour, minute, second = time_point.get_hour_minute_second()
254 microsecond = int(1.0e6 * (second - int(second)))
255 hour = int(hour)
256 minute = int(minute)
257 second = int(second)
258 date_time = datetime(
259 year, month, day, hour, minute, second, microsecond)
260 return date_time.strftime(print_format)
261
262 def get_datetime_strptime(self, time_point_str, parse_format):
263 """Use the datetime library's strptime as a fallback."""
264 _time = time.strptime(time_point_str, parse_format)
265 # NOTE: Neither time.strptime nor datetime.datetime.strptime can
266 # cope with %Z (time zone) that isn't 'UTC' or 'GMT'. There is no
267 # way to differentiate between an unrecognised zone (e.g. CET) and
268 # a bad time_point_str
269 return TimePoint(
270 year=_time.tm_year, month_of_year=_time.tm_mon,
271 day_of_month=_time.tm_mday, hour_of_day=_time.tm_hour,
272 minute_of_hour=_time.tm_min, second_of_minute=_time.tm_sec
273 )
274
275 def process_time_point_str(
276 self,
277 time_point_str=None,
278 offsets=None,
279 print_format=None,
280 ):
281 """Process time point string with optional offsets."""
282 time_point, parse_format = self.date_parse(time_point_str)
283 if offsets:
284 for offset in offsets:
285 time_point = self.date_shift(time_point, offset)
286 if print_format:
287 return self.date_format(print_format, time_point)
288 else:
289 return self.date_format(parse_format, time_point)
290
291 def diff_time_point_strs(
292 self,
293 time_point_str1,
294 time_point_str2,
295 offsets1=None,
296 offsets2=None,
297 print_format=None,
298 duration_print_format=None,
299 ):
300 """Calculate duration between 2 time point strings.
301
302 Each time point string may have optional offsets.
303 """
304 time_point1 = self.date_parse(time_point_str1)[0]
305 time_point2 = self.date_parse(time_point_str2)[0]
306 if offsets1:
307 for offset in offsets1:
308 time_point1 = self.date_shift(time_point1, offset)
309 if offsets2:
310 for offset in offsets2:
311 time_point2 = self.date_shift(time_point2, offset)
312 duration, sign = self.date_diff(time_point1, time_point2)
313 out = self.date_diff_format(print_format, duration, sign)
314 if duration_print_format:
315 return self.format_duration_str(out, duration_print_format)
316 else:
317 return out
318
319 def format_duration_str(self, duration_str, duration_print_format):
320 """Parse duration string, return as total of a unit.
321
322 Unit can be H, M or S (for hours, minutes or seconds).
323 """
324 duration = self.duration_parser.parse(
325 duration_str.replace('\\', '')) # allows negative durations
326 time = duration.get_seconds()
327 options = {'S': time, 'M': time / 60, 'H': time / 3600}
328 if duration_print_format.upper() in options:
329 # supplied duration format is valid
330 # (upper removes case-sensitivity)
331 return options[duration_print_format.upper()]
332 else:
333 # supplied duration format not valid
334 raise ValueError(
335 'Invalid duration print format, '
336 'should use one of H, M, S for (hours, minutes, seconds)'
337 )
338
339 def iter_recurrence_str(self, recurrence_str, print_format=None):
340 """Parse recurrence string, return time point strings iterator."""
341 recurrence = self.recurrence_parser.parse(recurrence_str)
342 for time_point in recurrence:
343 yield self.strftime(time_point, print_format)