1 | n/a | """Concrete date/time and related types. |
---|
2 | n/a | |
---|
3 | n/a | See http://www.iana.org/time-zones/repository/tz-link.html for |
---|
4 | n/a | time zone and DST data sources. |
---|
5 | n/a | """ |
---|
6 | n/a | |
---|
7 | n/a | import time as _time |
---|
8 | n/a | import math as _math |
---|
9 | n/a | |
---|
10 | n/a | def _cmp(x, y): |
---|
11 | n/a | return 0 if x == y else 1 if x > y else -1 |
---|
12 | n/a | |
---|
13 | n/a | MINYEAR = 1 |
---|
14 | n/a | MAXYEAR = 9999 |
---|
15 | n/a | _MAXORDINAL = 3652059 # date.max.toordinal() |
---|
16 | n/a | |
---|
17 | n/a | # Utility functions, adapted from Python's Demo/classes/Dates.py, which |
---|
18 | n/a | # also assumes the current Gregorian calendar indefinitely extended in |
---|
19 | n/a | # both directions. Difference: Dates.py calls January 1 of year 0 day |
---|
20 | n/a | # number 1. The code here calls January 1 of year 1 day number 1. This is |
---|
21 | n/a | # to match the definition of the "proleptic Gregorian" calendar in Dershowitz |
---|
22 | n/a | # and Reingold's "Calendrical Calculations", where it's the base calendar |
---|
23 | n/a | # for all computations. See the book for algorithms for converting between |
---|
24 | n/a | # proleptic Gregorian ordinals and many other calendar systems. |
---|
25 | n/a | |
---|
26 | n/a | # -1 is a placeholder for indexing purposes. |
---|
27 | n/a | _DAYS_IN_MONTH = [-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] |
---|
28 | n/a | |
---|
29 | n/a | _DAYS_BEFORE_MONTH = [-1] # -1 is a placeholder for indexing purposes. |
---|
30 | n/a | dbm = 0 |
---|
31 | n/a | for dim in _DAYS_IN_MONTH[1:]: |
---|
32 | n/a | _DAYS_BEFORE_MONTH.append(dbm) |
---|
33 | n/a | dbm += dim |
---|
34 | n/a | del dbm, dim |
---|
35 | n/a | |
---|
36 | n/a | def _is_leap(year): |
---|
37 | n/a | "year -> 1 if leap year, else 0." |
---|
38 | n/a | return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) |
---|
39 | n/a | |
---|
40 | n/a | def _days_before_year(year): |
---|
41 | n/a | "year -> number of days before January 1st of year." |
---|
42 | n/a | y = year - 1 |
---|
43 | n/a | return y*365 + y//4 - y//100 + y//400 |
---|
44 | n/a | |
---|
45 | n/a | def _days_in_month(year, month): |
---|
46 | n/a | "year, month -> number of days in that month in that year." |
---|
47 | n/a | assert 1 <= month <= 12, month |
---|
48 | n/a | if month == 2 and _is_leap(year): |
---|
49 | n/a | return 29 |
---|
50 | n/a | return _DAYS_IN_MONTH[month] |
---|
51 | n/a | |
---|
52 | n/a | def _days_before_month(year, month): |
---|
53 | n/a | "year, month -> number of days in year preceding first day of month." |
---|
54 | n/a | assert 1 <= month <= 12, 'month must be in 1..12' |
---|
55 | n/a | return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year)) |
---|
56 | n/a | |
---|
57 | n/a | def _ymd2ord(year, month, day): |
---|
58 | n/a | "year, month, day -> ordinal, considering 01-Jan-0001 as day 1." |
---|
59 | n/a | assert 1 <= month <= 12, 'month must be in 1..12' |
---|
60 | n/a | dim = _days_in_month(year, month) |
---|
61 | n/a | assert 1 <= day <= dim, ('day must be in 1..%d' % dim) |
---|
62 | n/a | return (_days_before_year(year) + |
---|
63 | n/a | _days_before_month(year, month) + |
---|
64 | n/a | day) |
---|
65 | n/a | |
---|
66 | n/a | _DI400Y = _days_before_year(401) # number of days in 400 years |
---|
67 | n/a | _DI100Y = _days_before_year(101) # " " " " 100 " |
---|
68 | n/a | _DI4Y = _days_before_year(5) # " " " " 4 " |
---|
69 | n/a | |
---|
70 | n/a | # A 4-year cycle has an extra leap day over what we'd get from pasting |
---|
71 | n/a | # together 4 single years. |
---|
72 | n/a | assert _DI4Y == 4 * 365 + 1 |
---|
73 | n/a | |
---|
74 | n/a | # Similarly, a 400-year cycle has an extra leap day over what we'd get from |
---|
75 | n/a | # pasting together 4 100-year cycles. |
---|
76 | n/a | assert _DI400Y == 4 * _DI100Y + 1 |
---|
77 | n/a | |
---|
78 | n/a | # OTOH, a 100-year cycle has one fewer leap day than we'd get from |
---|
79 | n/a | # pasting together 25 4-year cycles. |
---|
80 | n/a | assert _DI100Y == 25 * _DI4Y - 1 |
---|
81 | n/a | |
---|
82 | n/a | def _ord2ymd(n): |
---|
83 | n/a | "ordinal -> (year, month, day), considering 01-Jan-0001 as day 1." |
---|
84 | n/a | |
---|
85 | n/a | # n is a 1-based index, starting at 1-Jan-1. The pattern of leap years |
---|
86 | n/a | # repeats exactly every 400 years. The basic strategy is to find the |
---|
87 | n/a | # closest 400-year boundary at or before n, then work with the offset |
---|
88 | n/a | # from that boundary to n. Life is much clearer if we subtract 1 from |
---|
89 | n/a | # n first -- then the values of n at 400-year boundaries are exactly |
---|
90 | n/a | # those divisible by _DI400Y: |
---|
91 | n/a | # |
---|
92 | n/a | # D M Y n n-1 |
---|
93 | n/a | # -- --- ---- ---------- ---------------- |
---|
94 | n/a | # 31 Dec -400 -_DI400Y -_DI400Y -1 |
---|
95 | n/a | # 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary |
---|
96 | n/a | # ... |
---|
97 | n/a | # 30 Dec 000 -1 -2 |
---|
98 | n/a | # 31 Dec 000 0 -1 |
---|
99 | n/a | # 1 Jan 001 1 0 400-year boundary |
---|
100 | n/a | # 2 Jan 001 2 1 |
---|
101 | n/a | # 3 Jan 001 3 2 |
---|
102 | n/a | # ... |
---|
103 | n/a | # 31 Dec 400 _DI400Y _DI400Y -1 |
---|
104 | n/a | # 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary |
---|
105 | n/a | n -= 1 |
---|
106 | n/a | n400, n = divmod(n, _DI400Y) |
---|
107 | n/a | year = n400 * 400 + 1 # ..., -399, 1, 401, ... |
---|
108 | n/a | |
---|
109 | n/a | # Now n is the (non-negative) offset, in days, from January 1 of year, to |
---|
110 | n/a | # the desired date. Now compute how many 100-year cycles precede n. |
---|
111 | n/a | # Note that it's possible for n100 to equal 4! In that case 4 full |
---|
112 | n/a | # 100-year cycles precede the desired day, which implies the desired |
---|
113 | n/a | # day is December 31 at the end of a 400-year cycle. |
---|
114 | n/a | n100, n = divmod(n, _DI100Y) |
---|
115 | n/a | |
---|
116 | n/a | # Now compute how many 4-year cycles precede it. |
---|
117 | n/a | n4, n = divmod(n, _DI4Y) |
---|
118 | n/a | |
---|
119 | n/a | # And now how many single years. Again n1 can be 4, and again meaning |
---|
120 | n/a | # that the desired day is December 31 at the end of the 4-year cycle. |
---|
121 | n/a | n1, n = divmod(n, 365) |
---|
122 | n/a | |
---|
123 | n/a | year += n100 * 100 + n4 * 4 + n1 |
---|
124 | n/a | if n1 == 4 or n100 == 4: |
---|
125 | n/a | assert n == 0 |
---|
126 | n/a | return year-1, 12, 31 |
---|
127 | n/a | |
---|
128 | n/a | # Now the year is correct, and n is the offset from January 1. We find |
---|
129 | n/a | # the month via an estimate that's either exact or one too large. |
---|
130 | n/a | leapyear = n1 == 3 and (n4 != 24 or n100 == 3) |
---|
131 | n/a | assert leapyear == _is_leap(year) |
---|
132 | n/a | month = (n + 50) >> 5 |
---|
133 | n/a | preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear) |
---|
134 | n/a | if preceding > n: # estimate is too large |
---|
135 | n/a | month -= 1 |
---|
136 | n/a | preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear) |
---|
137 | n/a | n -= preceding |
---|
138 | n/a | assert 0 <= n < _days_in_month(year, month) |
---|
139 | n/a | |
---|
140 | n/a | # Now the year and month are correct, and n is the offset from the |
---|
141 | n/a | # start of that month: we're done! |
---|
142 | n/a | return year, month, n+1 |
---|
143 | n/a | |
---|
144 | n/a | # Month and day names. For localized versions, see the calendar module. |
---|
145 | n/a | _MONTHNAMES = [None, "Jan", "Feb", "Mar", "Apr", "May", "Jun", |
---|
146 | n/a | "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] |
---|
147 | n/a | _DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] |
---|
148 | n/a | |
---|
149 | n/a | |
---|
150 | n/a | def _build_struct_time(y, m, d, hh, mm, ss, dstflag): |
---|
151 | n/a | wday = (_ymd2ord(y, m, d) + 6) % 7 |
---|
152 | n/a | dnum = _days_before_month(y, m) + d |
---|
153 | n/a | return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag)) |
---|
154 | n/a | |
---|
155 | n/a | def _format_time(hh, mm, ss, us, timespec='auto'): |
---|
156 | n/a | specs = { |
---|
157 | n/a | 'hours': '{:02d}', |
---|
158 | n/a | 'minutes': '{:02d}:{:02d}', |
---|
159 | n/a | 'seconds': '{:02d}:{:02d}:{:02d}', |
---|
160 | n/a | 'milliseconds': '{:02d}:{:02d}:{:02d}.{:03d}', |
---|
161 | n/a | 'microseconds': '{:02d}:{:02d}:{:02d}.{:06d}' |
---|
162 | n/a | } |
---|
163 | n/a | |
---|
164 | n/a | if timespec == 'auto': |
---|
165 | n/a | # Skip trailing microseconds when us==0. |
---|
166 | n/a | timespec = 'microseconds' if us else 'seconds' |
---|
167 | n/a | elif timespec == 'milliseconds': |
---|
168 | n/a | us //= 1000 |
---|
169 | n/a | try: |
---|
170 | n/a | fmt = specs[timespec] |
---|
171 | n/a | except KeyError: |
---|
172 | n/a | raise ValueError('Unknown timespec value') |
---|
173 | n/a | else: |
---|
174 | n/a | return fmt.format(hh, mm, ss, us) |
---|
175 | n/a | |
---|
176 | n/a | # Correctly substitute for %z and %Z escapes in strftime formats. |
---|
177 | n/a | def _wrap_strftime(object, format, timetuple): |
---|
178 | n/a | # Don't call utcoffset() or tzname() unless actually needed. |
---|
179 | n/a | freplace = None # the string to use for %f |
---|
180 | n/a | zreplace = None # the string to use for %z |
---|
181 | n/a | Zreplace = None # the string to use for %Z |
---|
182 | n/a | |
---|
183 | n/a | # Scan format for %z and %Z escapes, replacing as needed. |
---|
184 | n/a | newformat = [] |
---|
185 | n/a | push = newformat.append |
---|
186 | n/a | i, n = 0, len(format) |
---|
187 | n/a | while i < n: |
---|
188 | n/a | ch = format[i] |
---|
189 | n/a | i += 1 |
---|
190 | n/a | if ch == '%': |
---|
191 | n/a | if i < n: |
---|
192 | n/a | ch = format[i] |
---|
193 | n/a | i += 1 |
---|
194 | n/a | if ch == 'f': |
---|
195 | n/a | if freplace is None: |
---|
196 | n/a | freplace = '%06d' % getattr(object, |
---|
197 | n/a | 'microsecond', 0) |
---|
198 | n/a | newformat.append(freplace) |
---|
199 | n/a | elif ch == 'z': |
---|
200 | n/a | if zreplace is None: |
---|
201 | n/a | zreplace = "" |
---|
202 | n/a | if hasattr(object, "utcoffset"): |
---|
203 | n/a | offset = object.utcoffset() |
---|
204 | n/a | if offset is not None: |
---|
205 | n/a | sign = '+' |
---|
206 | n/a | if offset.days < 0: |
---|
207 | n/a | offset = -offset |
---|
208 | n/a | sign = '-' |
---|
209 | n/a | h, m = divmod(offset, timedelta(hours=1)) |
---|
210 | n/a | assert not m % timedelta(minutes=1), "whole minute" |
---|
211 | n/a | m //= timedelta(minutes=1) |
---|
212 | n/a | zreplace = '%c%02d%02d' % (sign, h, m) |
---|
213 | n/a | assert '%' not in zreplace |
---|
214 | n/a | newformat.append(zreplace) |
---|
215 | n/a | elif ch == 'Z': |
---|
216 | n/a | if Zreplace is None: |
---|
217 | n/a | Zreplace = "" |
---|
218 | n/a | if hasattr(object, "tzname"): |
---|
219 | n/a | s = object.tzname() |
---|
220 | n/a | if s is not None: |
---|
221 | n/a | # strftime is going to have at this: escape % |
---|
222 | n/a | Zreplace = s.replace('%', '%%') |
---|
223 | n/a | newformat.append(Zreplace) |
---|
224 | n/a | else: |
---|
225 | n/a | push('%') |
---|
226 | n/a | push(ch) |
---|
227 | n/a | else: |
---|
228 | n/a | push('%') |
---|
229 | n/a | else: |
---|
230 | n/a | push(ch) |
---|
231 | n/a | newformat = "".join(newformat) |
---|
232 | n/a | return _time.strftime(newformat, timetuple) |
---|
233 | n/a | |
---|
234 | n/a | # Just raise TypeError if the arg isn't None or a string. |
---|
235 | n/a | def _check_tzname(name): |
---|
236 | n/a | if name is not None and not isinstance(name, str): |
---|
237 | n/a | raise TypeError("tzinfo.tzname() must return None or string, " |
---|
238 | n/a | "not '%s'" % type(name)) |
---|
239 | n/a | |
---|
240 | n/a | # name is the offset-producing method, "utcoffset" or "dst". |
---|
241 | n/a | # offset is what it returned. |
---|
242 | n/a | # If offset isn't None or timedelta, raises TypeError. |
---|
243 | n/a | # If offset is None, returns None. |
---|
244 | n/a | # Else offset is checked for being in range, and a whole # of minutes. |
---|
245 | n/a | # If it is, its integer value is returned. Else ValueError is raised. |
---|
246 | n/a | def _check_utc_offset(name, offset): |
---|
247 | n/a | assert name in ("utcoffset", "dst") |
---|
248 | n/a | if offset is None: |
---|
249 | n/a | return |
---|
250 | n/a | if not isinstance(offset, timedelta): |
---|
251 | n/a | raise TypeError("tzinfo.%s() must return None " |
---|
252 | n/a | "or timedelta, not '%s'" % (name, type(offset))) |
---|
253 | n/a | if offset.microseconds: |
---|
254 | n/a | raise ValueError("tzinfo.%s() must return a whole number " |
---|
255 | n/a | "of seconds, got %s" % (name, offset)) |
---|
256 | n/a | if not -timedelta(1) < offset < timedelta(1): |
---|
257 | n/a | raise ValueError("%s()=%s, must be strictly between " |
---|
258 | n/a | "-timedelta(hours=24) and timedelta(hours=24)" % |
---|
259 | n/a | (name, offset)) |
---|
260 | n/a | |
---|
261 | n/a | def _check_int_field(value): |
---|
262 | n/a | if isinstance(value, int): |
---|
263 | n/a | return value |
---|
264 | n/a | if not isinstance(value, float): |
---|
265 | n/a | try: |
---|
266 | n/a | value = value.__int__() |
---|
267 | n/a | except AttributeError: |
---|
268 | n/a | pass |
---|
269 | n/a | else: |
---|
270 | n/a | if isinstance(value, int): |
---|
271 | n/a | return value |
---|
272 | n/a | raise TypeError('__int__ returned non-int (type %s)' % |
---|
273 | n/a | type(value).__name__) |
---|
274 | n/a | raise TypeError('an integer is required (got type %s)' % |
---|
275 | n/a | type(value).__name__) |
---|
276 | n/a | raise TypeError('integer argument expected, got float') |
---|
277 | n/a | |
---|
278 | n/a | def _check_date_fields(year, month, day): |
---|
279 | n/a | year = _check_int_field(year) |
---|
280 | n/a | month = _check_int_field(month) |
---|
281 | n/a | day = _check_int_field(day) |
---|
282 | n/a | if not MINYEAR <= year <= MAXYEAR: |
---|
283 | n/a | raise ValueError('year must be in %d..%d' % (MINYEAR, MAXYEAR), year) |
---|
284 | n/a | if not 1 <= month <= 12: |
---|
285 | n/a | raise ValueError('month must be in 1..12', month) |
---|
286 | n/a | dim = _days_in_month(year, month) |
---|
287 | n/a | if not 1 <= day <= dim: |
---|
288 | n/a | raise ValueError('day must be in 1..%d' % dim, day) |
---|
289 | n/a | return year, month, day |
---|
290 | n/a | |
---|
291 | n/a | def _check_time_fields(hour, minute, second, microsecond, fold): |
---|
292 | n/a | hour = _check_int_field(hour) |
---|
293 | n/a | minute = _check_int_field(minute) |
---|
294 | n/a | second = _check_int_field(second) |
---|
295 | n/a | microsecond = _check_int_field(microsecond) |
---|
296 | n/a | if not 0 <= hour <= 23: |
---|
297 | n/a | raise ValueError('hour must be in 0..23', hour) |
---|
298 | n/a | if not 0 <= minute <= 59: |
---|
299 | n/a | raise ValueError('minute must be in 0..59', minute) |
---|
300 | n/a | if not 0 <= second <= 59: |
---|
301 | n/a | raise ValueError('second must be in 0..59', second) |
---|
302 | n/a | if not 0 <= microsecond <= 999999: |
---|
303 | n/a | raise ValueError('microsecond must be in 0..999999', microsecond) |
---|
304 | n/a | if fold not in (0, 1): |
---|
305 | n/a | raise ValueError('fold must be either 0 or 1', fold) |
---|
306 | n/a | return hour, minute, second, microsecond, fold |
---|
307 | n/a | |
---|
308 | n/a | def _check_tzinfo_arg(tz): |
---|
309 | n/a | if tz is not None and not isinstance(tz, tzinfo): |
---|
310 | n/a | raise TypeError("tzinfo argument must be None or of a tzinfo subclass") |
---|
311 | n/a | |
---|
312 | n/a | def _cmperror(x, y): |
---|
313 | n/a | raise TypeError("can't compare '%s' to '%s'" % ( |
---|
314 | n/a | type(x).__name__, type(y).__name__)) |
---|
315 | n/a | |
---|
316 | n/a | def _divide_and_round(a, b): |
---|
317 | n/a | """divide a by b and round result to the nearest integer |
---|
318 | n/a | |
---|
319 | n/a | When the ratio is exactly half-way between two integers, |
---|
320 | n/a | the even integer is returned. |
---|
321 | n/a | """ |
---|
322 | n/a | # Based on the reference implementation for divmod_near |
---|
323 | n/a | # in Objects/longobject.c. |
---|
324 | n/a | q, r = divmod(a, b) |
---|
325 | n/a | # round up if either r / b > 0.5, or r / b == 0.5 and q is odd. |
---|
326 | n/a | # The expression r / b > 0.5 is equivalent to 2 * r > b if b is |
---|
327 | n/a | # positive, 2 * r < b if b negative. |
---|
328 | n/a | r *= 2 |
---|
329 | n/a | greater_than_half = r > b if b > 0 else r < b |
---|
330 | n/a | if greater_than_half or r == b and q % 2 == 1: |
---|
331 | n/a | q += 1 |
---|
332 | n/a | |
---|
333 | n/a | return q |
---|
334 | n/a | |
---|
335 | n/a | |
---|
336 | n/a | class timedelta: |
---|
337 | n/a | """Represent the difference between two datetime objects. |
---|
338 | n/a | |
---|
339 | n/a | Supported operators: |
---|
340 | n/a | |
---|
341 | n/a | - add, subtract timedelta |
---|
342 | n/a | - unary plus, minus, abs |
---|
343 | n/a | - compare to timedelta |
---|
344 | n/a | - multiply, divide by int |
---|
345 | n/a | |
---|
346 | n/a | In addition, datetime supports subtraction of two datetime objects |
---|
347 | n/a | returning a timedelta, and addition or subtraction of a datetime |
---|
348 | n/a | and a timedelta giving a datetime. |
---|
349 | n/a | |
---|
350 | n/a | Representation: (days, seconds, microseconds). Why? Because I |
---|
351 | n/a | felt like it. |
---|
352 | n/a | """ |
---|
353 | n/a | __slots__ = '_days', '_seconds', '_microseconds', '_hashcode' |
---|
354 | n/a | |
---|
355 | n/a | def __new__(cls, days=0, seconds=0, microseconds=0, |
---|
356 | n/a | milliseconds=0, minutes=0, hours=0, weeks=0): |
---|
357 | n/a | # Doing this efficiently and accurately in C is going to be difficult |
---|
358 | n/a | # and error-prone, due to ubiquitous overflow possibilities, and that |
---|
359 | n/a | # C double doesn't have enough bits of precision to represent |
---|
360 | n/a | # microseconds over 10K years faithfully. The code here tries to make |
---|
361 | n/a | # explicit where go-fast assumptions can be relied on, in order to |
---|
362 | n/a | # guide the C implementation; it's way more convoluted than speed- |
---|
363 | n/a | # ignoring auto-overflow-to-long idiomatic Python could be. |
---|
364 | n/a | |
---|
365 | n/a | # XXX Check that all inputs are ints or floats. |
---|
366 | n/a | |
---|
367 | n/a | # Final values, all integer. |
---|
368 | n/a | # s and us fit in 32-bit signed ints; d isn't bounded. |
---|
369 | n/a | d = s = us = 0 |
---|
370 | n/a | |
---|
371 | n/a | # Normalize everything to days, seconds, microseconds. |
---|
372 | n/a | days += weeks*7 |
---|
373 | n/a | seconds += minutes*60 + hours*3600 |
---|
374 | n/a | microseconds += milliseconds*1000 |
---|
375 | n/a | |
---|
376 | n/a | # Get rid of all fractions, and normalize s and us. |
---|
377 | n/a | # Take a deep breath <wink>. |
---|
378 | n/a | if isinstance(days, float): |
---|
379 | n/a | dayfrac, days = _math.modf(days) |
---|
380 | n/a | daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.)) |
---|
381 | n/a | assert daysecondswhole == int(daysecondswhole) # can't overflow |
---|
382 | n/a | s = int(daysecondswhole) |
---|
383 | n/a | assert days == int(days) |
---|
384 | n/a | d = int(days) |
---|
385 | n/a | else: |
---|
386 | n/a | daysecondsfrac = 0.0 |
---|
387 | n/a | d = days |
---|
388 | n/a | assert isinstance(daysecondsfrac, float) |
---|
389 | n/a | assert abs(daysecondsfrac) <= 1.0 |
---|
390 | n/a | assert isinstance(d, int) |
---|
391 | n/a | assert abs(s) <= 24 * 3600 |
---|
392 | n/a | # days isn't referenced again before redefinition |
---|
393 | n/a | |
---|
394 | n/a | if isinstance(seconds, float): |
---|
395 | n/a | secondsfrac, seconds = _math.modf(seconds) |
---|
396 | n/a | assert seconds == int(seconds) |
---|
397 | n/a | seconds = int(seconds) |
---|
398 | n/a | secondsfrac += daysecondsfrac |
---|
399 | n/a | assert abs(secondsfrac) <= 2.0 |
---|
400 | n/a | else: |
---|
401 | n/a | secondsfrac = daysecondsfrac |
---|
402 | n/a | # daysecondsfrac isn't referenced again |
---|
403 | n/a | assert isinstance(secondsfrac, float) |
---|
404 | n/a | assert abs(secondsfrac) <= 2.0 |
---|
405 | n/a | |
---|
406 | n/a | assert isinstance(seconds, int) |
---|
407 | n/a | days, seconds = divmod(seconds, 24*3600) |
---|
408 | n/a | d += days |
---|
409 | n/a | s += int(seconds) # can't overflow |
---|
410 | n/a | assert isinstance(s, int) |
---|
411 | n/a | assert abs(s) <= 2 * 24 * 3600 |
---|
412 | n/a | # seconds isn't referenced again before redefinition |
---|
413 | n/a | |
---|
414 | n/a | usdouble = secondsfrac * 1e6 |
---|
415 | n/a | assert abs(usdouble) < 2.1e6 # exact value not critical |
---|
416 | n/a | # secondsfrac isn't referenced again |
---|
417 | n/a | |
---|
418 | n/a | if isinstance(microseconds, float): |
---|
419 | n/a | microseconds = round(microseconds + usdouble) |
---|
420 | n/a | seconds, microseconds = divmod(microseconds, 1000000) |
---|
421 | n/a | days, seconds = divmod(seconds, 24*3600) |
---|
422 | n/a | d += days |
---|
423 | n/a | s += seconds |
---|
424 | n/a | else: |
---|
425 | n/a | microseconds = int(microseconds) |
---|
426 | n/a | seconds, microseconds = divmod(microseconds, 1000000) |
---|
427 | n/a | days, seconds = divmod(seconds, 24*3600) |
---|
428 | n/a | d += days |
---|
429 | n/a | s += seconds |
---|
430 | n/a | microseconds = round(microseconds + usdouble) |
---|
431 | n/a | assert isinstance(s, int) |
---|
432 | n/a | assert isinstance(microseconds, int) |
---|
433 | n/a | assert abs(s) <= 3 * 24 * 3600 |
---|
434 | n/a | assert abs(microseconds) < 3.1e6 |
---|
435 | n/a | |
---|
436 | n/a | # Just a little bit of carrying possible for microseconds and seconds. |
---|
437 | n/a | seconds, us = divmod(microseconds, 1000000) |
---|
438 | n/a | s += seconds |
---|
439 | n/a | days, s = divmod(s, 24*3600) |
---|
440 | n/a | d += days |
---|
441 | n/a | |
---|
442 | n/a | assert isinstance(d, int) |
---|
443 | n/a | assert isinstance(s, int) and 0 <= s < 24*3600 |
---|
444 | n/a | assert isinstance(us, int) and 0 <= us < 1000000 |
---|
445 | n/a | |
---|
446 | n/a | if abs(d) > 999999999: |
---|
447 | n/a | raise OverflowError("timedelta # of days is too large: %d" % d) |
---|
448 | n/a | |
---|
449 | n/a | self = object.__new__(cls) |
---|
450 | n/a | self._days = d |
---|
451 | n/a | self._seconds = s |
---|
452 | n/a | self._microseconds = us |
---|
453 | n/a | self._hashcode = -1 |
---|
454 | n/a | return self |
---|
455 | n/a | |
---|
456 | n/a | def __repr__(self): |
---|
457 | n/a | if self._microseconds: |
---|
458 | n/a | return "%s.%s(%d, %d, %d)" % (self.__class__.__module__, |
---|
459 | n/a | self.__class__.__qualname__, |
---|
460 | n/a | self._days, |
---|
461 | n/a | self._seconds, |
---|
462 | n/a | self._microseconds) |
---|
463 | n/a | if self._seconds: |
---|
464 | n/a | return "%s.%s(%d, %d)" % (self.__class__.__module__, |
---|
465 | n/a | self.__class__.__qualname__, |
---|
466 | n/a | self._days, |
---|
467 | n/a | self._seconds) |
---|
468 | n/a | return "%s.%s(%d)" % (self.__class__.__module__, |
---|
469 | n/a | self.__class__.__qualname__, |
---|
470 | n/a | self._days) |
---|
471 | n/a | |
---|
472 | n/a | def __str__(self): |
---|
473 | n/a | mm, ss = divmod(self._seconds, 60) |
---|
474 | n/a | hh, mm = divmod(mm, 60) |
---|
475 | n/a | s = "%d:%02d:%02d" % (hh, mm, ss) |
---|
476 | n/a | if self._days: |
---|
477 | n/a | def plural(n): |
---|
478 | n/a | return n, abs(n) != 1 and "s" or "" |
---|
479 | n/a | s = ("%d day%s, " % plural(self._days)) + s |
---|
480 | n/a | if self._microseconds: |
---|
481 | n/a | s = s + ".%06d" % self._microseconds |
---|
482 | n/a | return s |
---|
483 | n/a | |
---|
484 | n/a | def total_seconds(self): |
---|
485 | n/a | """Total seconds in the duration.""" |
---|
486 | n/a | return ((self.days * 86400 + self.seconds) * 10**6 + |
---|
487 | n/a | self.microseconds) / 10**6 |
---|
488 | n/a | |
---|
489 | n/a | # Read-only field accessors |
---|
490 | n/a | @property |
---|
491 | n/a | def days(self): |
---|
492 | n/a | """days""" |
---|
493 | n/a | return self._days |
---|
494 | n/a | |
---|
495 | n/a | @property |
---|
496 | n/a | def seconds(self): |
---|
497 | n/a | """seconds""" |
---|
498 | n/a | return self._seconds |
---|
499 | n/a | |
---|
500 | n/a | @property |
---|
501 | n/a | def microseconds(self): |
---|
502 | n/a | """microseconds""" |
---|
503 | n/a | return self._microseconds |
---|
504 | n/a | |
---|
505 | n/a | def __add__(self, other): |
---|
506 | n/a | if isinstance(other, timedelta): |
---|
507 | n/a | # for CPython compatibility, we cannot use |
---|
508 | n/a | # our __class__ here, but need a real timedelta |
---|
509 | n/a | return timedelta(self._days + other._days, |
---|
510 | n/a | self._seconds + other._seconds, |
---|
511 | n/a | self._microseconds + other._microseconds) |
---|
512 | n/a | return NotImplemented |
---|
513 | n/a | |
---|
514 | n/a | __radd__ = __add__ |
---|
515 | n/a | |
---|
516 | n/a | def __sub__(self, other): |
---|
517 | n/a | if isinstance(other, timedelta): |
---|
518 | n/a | # for CPython compatibility, we cannot use |
---|
519 | n/a | # our __class__ here, but need a real timedelta |
---|
520 | n/a | return timedelta(self._days - other._days, |
---|
521 | n/a | self._seconds - other._seconds, |
---|
522 | n/a | self._microseconds - other._microseconds) |
---|
523 | n/a | return NotImplemented |
---|
524 | n/a | |
---|
525 | n/a | def __rsub__(self, other): |
---|
526 | n/a | if isinstance(other, timedelta): |
---|
527 | n/a | return -self + other |
---|
528 | n/a | return NotImplemented |
---|
529 | n/a | |
---|
530 | n/a | def __neg__(self): |
---|
531 | n/a | # for CPython compatibility, we cannot use |
---|
532 | n/a | # our __class__ here, but need a real timedelta |
---|
533 | n/a | return timedelta(-self._days, |
---|
534 | n/a | -self._seconds, |
---|
535 | n/a | -self._microseconds) |
---|
536 | n/a | |
---|
537 | n/a | def __pos__(self): |
---|
538 | n/a | return self |
---|
539 | n/a | |
---|
540 | n/a | def __abs__(self): |
---|
541 | n/a | if self._days < 0: |
---|
542 | n/a | return -self |
---|
543 | n/a | else: |
---|
544 | n/a | return self |
---|
545 | n/a | |
---|
546 | n/a | def __mul__(self, other): |
---|
547 | n/a | if isinstance(other, int): |
---|
548 | n/a | # for CPython compatibility, we cannot use |
---|
549 | n/a | # our __class__ here, but need a real timedelta |
---|
550 | n/a | return timedelta(self._days * other, |
---|
551 | n/a | self._seconds * other, |
---|
552 | n/a | self._microseconds * other) |
---|
553 | n/a | if isinstance(other, float): |
---|
554 | n/a | usec = self._to_microseconds() |
---|
555 | n/a | a, b = other.as_integer_ratio() |
---|
556 | n/a | return timedelta(0, 0, _divide_and_round(usec * a, b)) |
---|
557 | n/a | return NotImplemented |
---|
558 | n/a | |
---|
559 | n/a | __rmul__ = __mul__ |
---|
560 | n/a | |
---|
561 | n/a | def _to_microseconds(self): |
---|
562 | n/a | return ((self._days * (24*3600) + self._seconds) * 1000000 + |
---|
563 | n/a | self._microseconds) |
---|
564 | n/a | |
---|
565 | n/a | def __floordiv__(self, other): |
---|
566 | n/a | if not isinstance(other, (int, timedelta)): |
---|
567 | n/a | return NotImplemented |
---|
568 | n/a | usec = self._to_microseconds() |
---|
569 | n/a | if isinstance(other, timedelta): |
---|
570 | n/a | return usec // other._to_microseconds() |
---|
571 | n/a | if isinstance(other, int): |
---|
572 | n/a | return timedelta(0, 0, usec // other) |
---|
573 | n/a | |
---|
574 | n/a | def __truediv__(self, other): |
---|
575 | n/a | if not isinstance(other, (int, float, timedelta)): |
---|
576 | n/a | return NotImplemented |
---|
577 | n/a | usec = self._to_microseconds() |
---|
578 | n/a | if isinstance(other, timedelta): |
---|
579 | n/a | return usec / other._to_microseconds() |
---|
580 | n/a | if isinstance(other, int): |
---|
581 | n/a | return timedelta(0, 0, _divide_and_round(usec, other)) |
---|
582 | n/a | if isinstance(other, float): |
---|
583 | n/a | a, b = other.as_integer_ratio() |
---|
584 | n/a | return timedelta(0, 0, _divide_and_round(b * usec, a)) |
---|
585 | n/a | |
---|
586 | n/a | def __mod__(self, other): |
---|
587 | n/a | if isinstance(other, timedelta): |
---|
588 | n/a | r = self._to_microseconds() % other._to_microseconds() |
---|
589 | n/a | return timedelta(0, 0, r) |
---|
590 | n/a | return NotImplemented |
---|
591 | n/a | |
---|
592 | n/a | def __divmod__(self, other): |
---|
593 | n/a | if isinstance(other, timedelta): |
---|
594 | n/a | q, r = divmod(self._to_microseconds(), |
---|
595 | n/a | other._to_microseconds()) |
---|
596 | n/a | return q, timedelta(0, 0, r) |
---|
597 | n/a | return NotImplemented |
---|
598 | n/a | |
---|
599 | n/a | # Comparisons of timedelta objects with other. |
---|
600 | n/a | |
---|
601 | n/a | def __eq__(self, other): |
---|
602 | n/a | if isinstance(other, timedelta): |
---|
603 | n/a | return self._cmp(other) == 0 |
---|
604 | n/a | else: |
---|
605 | n/a | return False |
---|
606 | n/a | |
---|
607 | n/a | def __le__(self, other): |
---|
608 | n/a | if isinstance(other, timedelta): |
---|
609 | n/a | return self._cmp(other) <= 0 |
---|
610 | n/a | else: |
---|
611 | n/a | _cmperror(self, other) |
---|
612 | n/a | |
---|
613 | n/a | def __lt__(self, other): |
---|
614 | n/a | if isinstance(other, timedelta): |
---|
615 | n/a | return self._cmp(other) < 0 |
---|
616 | n/a | else: |
---|
617 | n/a | _cmperror(self, other) |
---|
618 | n/a | |
---|
619 | n/a | def __ge__(self, other): |
---|
620 | n/a | if isinstance(other, timedelta): |
---|
621 | n/a | return self._cmp(other) >= 0 |
---|
622 | n/a | else: |
---|
623 | n/a | _cmperror(self, other) |
---|
624 | n/a | |
---|
625 | n/a | def __gt__(self, other): |
---|
626 | n/a | if isinstance(other, timedelta): |
---|
627 | n/a | return self._cmp(other) > 0 |
---|
628 | n/a | else: |
---|
629 | n/a | _cmperror(self, other) |
---|
630 | n/a | |
---|
631 | n/a | def _cmp(self, other): |
---|
632 | n/a | assert isinstance(other, timedelta) |
---|
633 | n/a | return _cmp(self._getstate(), other._getstate()) |
---|
634 | n/a | |
---|
635 | n/a | def __hash__(self): |
---|
636 | n/a | if self._hashcode == -1: |
---|
637 | n/a | self._hashcode = hash(self._getstate()) |
---|
638 | n/a | return self._hashcode |
---|
639 | n/a | |
---|
640 | n/a | def __bool__(self): |
---|
641 | n/a | return (self._days != 0 or |
---|
642 | n/a | self._seconds != 0 or |
---|
643 | n/a | self._microseconds != 0) |
---|
644 | n/a | |
---|
645 | n/a | # Pickle support. |
---|
646 | n/a | |
---|
647 | n/a | def _getstate(self): |
---|
648 | n/a | return (self._days, self._seconds, self._microseconds) |
---|
649 | n/a | |
---|
650 | n/a | def __reduce__(self): |
---|
651 | n/a | return (self.__class__, self._getstate()) |
---|
652 | n/a | |
---|
653 | n/a | timedelta.min = timedelta(-999999999) |
---|
654 | n/a | timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59, |
---|
655 | n/a | microseconds=999999) |
---|
656 | n/a | timedelta.resolution = timedelta(microseconds=1) |
---|
657 | n/a | |
---|
658 | n/a | class date: |
---|
659 | n/a | """Concrete date type. |
---|
660 | n/a | |
---|
661 | n/a | Constructors: |
---|
662 | n/a | |
---|
663 | n/a | __new__() |
---|
664 | n/a | fromtimestamp() |
---|
665 | n/a | today() |
---|
666 | n/a | fromordinal() |
---|
667 | n/a | |
---|
668 | n/a | Operators: |
---|
669 | n/a | |
---|
670 | n/a | __repr__, __str__ |
---|
671 | n/a | __eq__, __le__, __lt__, __ge__, __gt__, __hash__ |
---|
672 | n/a | __add__, __radd__, __sub__ (add/radd only with timedelta arg) |
---|
673 | n/a | |
---|
674 | n/a | Methods: |
---|
675 | n/a | |
---|
676 | n/a | timetuple() |
---|
677 | n/a | toordinal() |
---|
678 | n/a | weekday() |
---|
679 | n/a | isoweekday(), isocalendar(), isoformat() |
---|
680 | n/a | ctime() |
---|
681 | n/a | strftime() |
---|
682 | n/a | |
---|
683 | n/a | Properties (readonly): |
---|
684 | n/a | year, month, day |
---|
685 | n/a | """ |
---|
686 | n/a | __slots__ = '_year', '_month', '_day', '_hashcode' |
---|
687 | n/a | |
---|
688 | n/a | def __new__(cls, year, month=None, day=None): |
---|
689 | n/a | """Constructor. |
---|
690 | n/a | |
---|
691 | n/a | Arguments: |
---|
692 | n/a | |
---|
693 | n/a | year, month, day (required, base 1) |
---|
694 | n/a | """ |
---|
695 | n/a | if month is None and isinstance(year, bytes) and len(year) == 4 and \ |
---|
696 | n/a | 1 <= year[2] <= 12: |
---|
697 | n/a | # Pickle support |
---|
698 | n/a | self = object.__new__(cls) |
---|
699 | n/a | self.__setstate(year) |
---|
700 | n/a | self._hashcode = -1 |
---|
701 | n/a | return self |
---|
702 | n/a | year, month, day = _check_date_fields(year, month, day) |
---|
703 | n/a | self = object.__new__(cls) |
---|
704 | n/a | self._year = year |
---|
705 | n/a | self._month = month |
---|
706 | n/a | self._day = day |
---|
707 | n/a | self._hashcode = -1 |
---|
708 | n/a | return self |
---|
709 | n/a | |
---|
710 | n/a | # Additional constructors |
---|
711 | n/a | |
---|
712 | n/a | @classmethod |
---|
713 | n/a | def fromtimestamp(cls, t): |
---|
714 | n/a | "Construct a date from a POSIX timestamp (like time.time())." |
---|
715 | n/a | y, m, d, hh, mm, ss, weekday, jday, dst = _time.localtime(t) |
---|
716 | n/a | return cls(y, m, d) |
---|
717 | n/a | |
---|
718 | n/a | @classmethod |
---|
719 | n/a | def today(cls): |
---|
720 | n/a | "Construct a date from time.time()." |
---|
721 | n/a | t = _time.time() |
---|
722 | n/a | return cls.fromtimestamp(t) |
---|
723 | n/a | |
---|
724 | n/a | @classmethod |
---|
725 | n/a | def fromordinal(cls, n): |
---|
726 | n/a | """Construct a date from a proleptic Gregorian ordinal. |
---|
727 | n/a | |
---|
728 | n/a | January 1 of year 1 is day 1. Only the year, month and day are |
---|
729 | n/a | non-zero in the result. |
---|
730 | n/a | """ |
---|
731 | n/a | y, m, d = _ord2ymd(n) |
---|
732 | n/a | return cls(y, m, d) |
---|
733 | n/a | |
---|
734 | n/a | # Conversions to string |
---|
735 | n/a | |
---|
736 | n/a | def __repr__(self): |
---|
737 | n/a | """Convert to formal string, for repr(). |
---|
738 | n/a | |
---|
739 | n/a | >>> dt = datetime(2010, 1, 1) |
---|
740 | n/a | >>> repr(dt) |
---|
741 | n/a | 'datetime.datetime(2010, 1, 1, 0, 0)' |
---|
742 | n/a | |
---|
743 | n/a | >>> dt = datetime(2010, 1, 1, tzinfo=timezone.utc) |
---|
744 | n/a | >>> repr(dt) |
---|
745 | n/a | 'datetime.datetime(2010, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)' |
---|
746 | n/a | """ |
---|
747 | n/a | return "%s.%s(%d, %d, %d)" % (self.__class__.__module__, |
---|
748 | n/a | self.__class__.__qualname__, |
---|
749 | n/a | self._year, |
---|
750 | n/a | self._month, |
---|
751 | n/a | self._day) |
---|
752 | n/a | # XXX These shouldn't depend on time.localtime(), because that |
---|
753 | n/a | # clips the usable dates to [1970 .. 2038). At least ctime() is |
---|
754 | n/a | # easily done without using strftime() -- that's better too because |
---|
755 | n/a | # strftime("%c", ...) is locale specific. |
---|
756 | n/a | |
---|
757 | n/a | |
---|
758 | n/a | def ctime(self): |
---|
759 | n/a | "Return ctime() style string." |
---|
760 | n/a | weekday = self.toordinal() % 7 or 7 |
---|
761 | n/a | return "%s %s %2d 00:00:00 %04d" % ( |
---|
762 | n/a | _DAYNAMES[weekday], |
---|
763 | n/a | _MONTHNAMES[self._month], |
---|
764 | n/a | self._day, self._year) |
---|
765 | n/a | |
---|
766 | n/a | def strftime(self, fmt): |
---|
767 | n/a | "Format using strftime()." |
---|
768 | n/a | return _wrap_strftime(self, fmt, self.timetuple()) |
---|
769 | n/a | |
---|
770 | n/a | def __format__(self, fmt): |
---|
771 | n/a | if not isinstance(fmt, str): |
---|
772 | n/a | raise TypeError("must be str, not %s" % type(fmt).__name__) |
---|
773 | n/a | if len(fmt) != 0: |
---|
774 | n/a | return self.strftime(fmt) |
---|
775 | n/a | return str(self) |
---|
776 | n/a | |
---|
777 | n/a | def isoformat(self): |
---|
778 | n/a | """Return the date formatted according to ISO. |
---|
779 | n/a | |
---|
780 | n/a | This is 'YYYY-MM-DD'. |
---|
781 | n/a | |
---|
782 | n/a | References: |
---|
783 | n/a | - http://www.w3.org/TR/NOTE-datetime |
---|
784 | n/a | - http://www.cl.cam.ac.uk/~mgk25/iso-time.html |
---|
785 | n/a | """ |
---|
786 | n/a | return "%04d-%02d-%02d" % (self._year, self._month, self._day) |
---|
787 | n/a | |
---|
788 | n/a | __str__ = isoformat |
---|
789 | n/a | |
---|
790 | n/a | # Read-only field accessors |
---|
791 | n/a | @property |
---|
792 | n/a | def year(self): |
---|
793 | n/a | """year (1-9999)""" |
---|
794 | n/a | return self._year |
---|
795 | n/a | |
---|
796 | n/a | @property |
---|
797 | n/a | def month(self): |
---|
798 | n/a | """month (1-12)""" |
---|
799 | n/a | return self._month |
---|
800 | n/a | |
---|
801 | n/a | @property |
---|
802 | n/a | def day(self): |
---|
803 | n/a | """day (1-31)""" |
---|
804 | n/a | return self._day |
---|
805 | n/a | |
---|
806 | n/a | # Standard conversions, __eq__, __le__, __lt__, __ge__, __gt__, |
---|
807 | n/a | # __hash__ (and helpers) |
---|
808 | n/a | |
---|
809 | n/a | def timetuple(self): |
---|
810 | n/a | "Return local time tuple compatible with time.localtime()." |
---|
811 | n/a | return _build_struct_time(self._year, self._month, self._day, |
---|
812 | n/a | 0, 0, 0, -1) |
---|
813 | n/a | |
---|
814 | n/a | def toordinal(self): |
---|
815 | n/a | """Return proleptic Gregorian ordinal for the year, month and day. |
---|
816 | n/a | |
---|
817 | n/a | January 1 of year 1 is day 1. Only the year, month and day values |
---|
818 | n/a | contribute to the result. |
---|
819 | n/a | """ |
---|
820 | n/a | return _ymd2ord(self._year, self._month, self._day) |
---|
821 | n/a | |
---|
822 | n/a | def replace(self, year=None, month=None, day=None): |
---|
823 | n/a | """Return a new date with new values for the specified fields.""" |
---|
824 | n/a | if year is None: |
---|
825 | n/a | year = self._year |
---|
826 | n/a | if month is None: |
---|
827 | n/a | month = self._month |
---|
828 | n/a | if day is None: |
---|
829 | n/a | day = self._day |
---|
830 | n/a | return date(year, month, day) |
---|
831 | n/a | |
---|
832 | n/a | # Comparisons of date objects with other. |
---|
833 | n/a | |
---|
834 | n/a | def __eq__(self, other): |
---|
835 | n/a | if isinstance(other, date): |
---|
836 | n/a | return self._cmp(other) == 0 |
---|
837 | n/a | return NotImplemented |
---|
838 | n/a | |
---|
839 | n/a | def __le__(self, other): |
---|
840 | n/a | if isinstance(other, date): |
---|
841 | n/a | return self._cmp(other) <= 0 |
---|
842 | n/a | return NotImplemented |
---|
843 | n/a | |
---|
844 | n/a | def __lt__(self, other): |
---|
845 | n/a | if isinstance(other, date): |
---|
846 | n/a | return self._cmp(other) < 0 |
---|
847 | n/a | return NotImplemented |
---|
848 | n/a | |
---|
849 | n/a | def __ge__(self, other): |
---|
850 | n/a | if isinstance(other, date): |
---|
851 | n/a | return self._cmp(other) >= 0 |
---|
852 | n/a | return NotImplemented |
---|
853 | n/a | |
---|
854 | n/a | def __gt__(self, other): |
---|
855 | n/a | if isinstance(other, date): |
---|
856 | n/a | return self._cmp(other) > 0 |
---|
857 | n/a | return NotImplemented |
---|
858 | n/a | |
---|
859 | n/a | def _cmp(self, other): |
---|
860 | n/a | assert isinstance(other, date) |
---|
861 | n/a | y, m, d = self._year, self._month, self._day |
---|
862 | n/a | y2, m2, d2 = other._year, other._month, other._day |
---|
863 | n/a | return _cmp((y, m, d), (y2, m2, d2)) |
---|
864 | n/a | |
---|
865 | n/a | def __hash__(self): |
---|
866 | n/a | "Hash." |
---|
867 | n/a | if self._hashcode == -1: |
---|
868 | n/a | self._hashcode = hash(self._getstate()) |
---|
869 | n/a | return self._hashcode |
---|
870 | n/a | |
---|
871 | n/a | # Computations |
---|
872 | n/a | |
---|
873 | n/a | def __add__(self, other): |
---|
874 | n/a | "Add a date to a timedelta." |
---|
875 | n/a | if isinstance(other, timedelta): |
---|
876 | n/a | o = self.toordinal() + other.days |
---|
877 | n/a | if 0 < o <= _MAXORDINAL: |
---|
878 | n/a | return date.fromordinal(o) |
---|
879 | n/a | raise OverflowError("result out of range") |
---|
880 | n/a | return NotImplemented |
---|
881 | n/a | |
---|
882 | n/a | __radd__ = __add__ |
---|
883 | n/a | |
---|
884 | n/a | def __sub__(self, other): |
---|
885 | n/a | """Subtract two dates, or a date and a timedelta.""" |
---|
886 | n/a | if isinstance(other, timedelta): |
---|
887 | n/a | return self + timedelta(-other.days) |
---|
888 | n/a | if isinstance(other, date): |
---|
889 | n/a | days1 = self.toordinal() |
---|
890 | n/a | days2 = other.toordinal() |
---|
891 | n/a | return timedelta(days1 - days2) |
---|
892 | n/a | return NotImplemented |
---|
893 | n/a | |
---|
894 | n/a | def weekday(self): |
---|
895 | n/a | "Return day of the week, where Monday == 0 ... Sunday == 6." |
---|
896 | n/a | return (self.toordinal() + 6) % 7 |
---|
897 | n/a | |
---|
898 | n/a | # Day-of-the-week and week-of-the-year, according to ISO |
---|
899 | n/a | |
---|
900 | n/a | def isoweekday(self): |
---|
901 | n/a | "Return day of the week, where Monday == 1 ... Sunday == 7." |
---|
902 | n/a | # 1-Jan-0001 is a Monday |
---|
903 | n/a | return self.toordinal() % 7 or 7 |
---|
904 | n/a | |
---|
905 | n/a | def isocalendar(self): |
---|
906 | n/a | """Return a 3-tuple containing ISO year, week number, and weekday. |
---|
907 | n/a | |
---|
908 | n/a | The first ISO week of the year is the (Mon-Sun) week |
---|
909 | n/a | containing the year's first Thursday; everything else derives |
---|
910 | n/a | from that. |
---|
911 | n/a | |
---|
912 | n/a | The first week is 1; Monday is 1 ... Sunday is 7. |
---|
913 | n/a | |
---|
914 | n/a | ISO calendar algorithm taken from |
---|
915 | n/a | http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm |
---|
916 | n/a | (used with permission) |
---|
917 | n/a | """ |
---|
918 | n/a | year = self._year |
---|
919 | n/a | week1monday = _isoweek1monday(year) |
---|
920 | n/a | today = _ymd2ord(self._year, self._month, self._day) |
---|
921 | n/a | # Internally, week and day have origin 0 |
---|
922 | n/a | week, day = divmod(today - week1monday, 7) |
---|
923 | n/a | if week < 0: |
---|
924 | n/a | year -= 1 |
---|
925 | n/a | week1monday = _isoweek1monday(year) |
---|
926 | n/a | week, day = divmod(today - week1monday, 7) |
---|
927 | n/a | elif week >= 52: |
---|
928 | n/a | if today >= _isoweek1monday(year+1): |
---|
929 | n/a | year += 1 |
---|
930 | n/a | week = 0 |
---|
931 | n/a | return year, week+1, day+1 |
---|
932 | n/a | |
---|
933 | n/a | # Pickle support. |
---|
934 | n/a | |
---|
935 | n/a | def _getstate(self): |
---|
936 | n/a | yhi, ylo = divmod(self._year, 256) |
---|
937 | n/a | return bytes([yhi, ylo, self._month, self._day]), |
---|
938 | n/a | |
---|
939 | n/a | def __setstate(self, string): |
---|
940 | n/a | yhi, ylo, self._month, self._day = string |
---|
941 | n/a | self._year = yhi * 256 + ylo |
---|
942 | n/a | |
---|
943 | n/a | def __reduce__(self): |
---|
944 | n/a | return (self.__class__, self._getstate()) |
---|
945 | n/a | |
---|
946 | n/a | _date_class = date # so functions w/ args named "date" can get at the class |
---|
947 | n/a | |
---|
948 | n/a | date.min = date(1, 1, 1) |
---|
949 | n/a | date.max = date(9999, 12, 31) |
---|
950 | n/a | date.resolution = timedelta(days=1) |
---|
951 | n/a | |
---|
952 | n/a | |
---|
953 | n/a | class tzinfo: |
---|
954 | n/a | """Abstract base class for time zone info classes. |
---|
955 | n/a | |
---|
956 | n/a | Subclasses must override the name(), utcoffset() and dst() methods. |
---|
957 | n/a | """ |
---|
958 | n/a | __slots__ = () |
---|
959 | n/a | |
---|
960 | n/a | def tzname(self, dt): |
---|
961 | n/a | "datetime -> string name of time zone." |
---|
962 | n/a | raise NotImplementedError("tzinfo subclass must override tzname()") |
---|
963 | n/a | |
---|
964 | n/a | def utcoffset(self, dt): |
---|
965 | n/a | "datetime -> minutes east of UTC (negative for west of UTC)" |
---|
966 | n/a | raise NotImplementedError("tzinfo subclass must override utcoffset()") |
---|
967 | n/a | |
---|
968 | n/a | def dst(self, dt): |
---|
969 | n/a | """datetime -> DST offset in minutes east of UTC. |
---|
970 | n/a | |
---|
971 | n/a | Return 0 if DST not in effect. utcoffset() must include the DST |
---|
972 | n/a | offset. |
---|
973 | n/a | """ |
---|
974 | n/a | raise NotImplementedError("tzinfo subclass must override dst()") |
---|
975 | n/a | |
---|
976 | n/a | def fromutc(self, dt): |
---|
977 | n/a | "datetime in UTC -> datetime in local time." |
---|
978 | n/a | |
---|
979 | n/a | if not isinstance(dt, datetime): |
---|
980 | n/a | raise TypeError("fromutc() requires a datetime argument") |
---|
981 | n/a | if dt.tzinfo is not self: |
---|
982 | n/a | raise ValueError("dt.tzinfo is not self") |
---|
983 | n/a | |
---|
984 | n/a | dtoff = dt.utcoffset() |
---|
985 | n/a | if dtoff is None: |
---|
986 | n/a | raise ValueError("fromutc() requires a non-None utcoffset() " |
---|
987 | n/a | "result") |
---|
988 | n/a | |
---|
989 | n/a | # See the long comment block at the end of this file for an |
---|
990 | n/a | # explanation of this algorithm. |
---|
991 | n/a | dtdst = dt.dst() |
---|
992 | n/a | if dtdst is None: |
---|
993 | n/a | raise ValueError("fromutc() requires a non-None dst() result") |
---|
994 | n/a | delta = dtoff - dtdst |
---|
995 | n/a | if delta: |
---|
996 | n/a | dt += delta |
---|
997 | n/a | dtdst = dt.dst() |
---|
998 | n/a | if dtdst is None: |
---|
999 | n/a | raise ValueError("fromutc(): dt.dst gave inconsistent " |
---|
1000 | n/a | "results; cannot convert") |
---|
1001 | n/a | return dt + dtdst |
---|
1002 | n/a | |
---|
1003 | n/a | # Pickle support. |
---|
1004 | n/a | |
---|
1005 | n/a | def __reduce__(self): |
---|
1006 | n/a | getinitargs = getattr(self, "__getinitargs__", None) |
---|
1007 | n/a | if getinitargs: |
---|
1008 | n/a | args = getinitargs() |
---|
1009 | n/a | else: |
---|
1010 | n/a | args = () |
---|
1011 | n/a | getstate = getattr(self, "__getstate__", None) |
---|
1012 | n/a | if getstate: |
---|
1013 | n/a | state = getstate() |
---|
1014 | n/a | else: |
---|
1015 | n/a | state = getattr(self, "__dict__", None) or None |
---|
1016 | n/a | if state is None: |
---|
1017 | n/a | return (self.__class__, args) |
---|
1018 | n/a | else: |
---|
1019 | n/a | return (self.__class__, args, state) |
---|
1020 | n/a | |
---|
1021 | n/a | _tzinfo_class = tzinfo |
---|
1022 | n/a | |
---|
1023 | n/a | class time: |
---|
1024 | n/a | """Time with time zone. |
---|
1025 | n/a | |
---|
1026 | n/a | Constructors: |
---|
1027 | n/a | |
---|
1028 | n/a | __new__() |
---|
1029 | n/a | |
---|
1030 | n/a | Operators: |
---|
1031 | n/a | |
---|
1032 | n/a | __repr__, __str__ |
---|
1033 | n/a | __eq__, __le__, __lt__, __ge__, __gt__, __hash__ |
---|
1034 | n/a | |
---|
1035 | n/a | Methods: |
---|
1036 | n/a | |
---|
1037 | n/a | strftime() |
---|
1038 | n/a | isoformat() |
---|
1039 | n/a | utcoffset() |
---|
1040 | n/a | tzname() |
---|
1041 | n/a | dst() |
---|
1042 | n/a | |
---|
1043 | n/a | Properties (readonly): |
---|
1044 | n/a | hour, minute, second, microsecond, tzinfo, fold |
---|
1045 | n/a | """ |
---|
1046 | n/a | __slots__ = '_hour', '_minute', '_second', '_microsecond', '_tzinfo', '_hashcode', '_fold' |
---|
1047 | n/a | |
---|
1048 | n/a | def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0): |
---|
1049 | n/a | """Constructor. |
---|
1050 | n/a | |
---|
1051 | n/a | Arguments: |
---|
1052 | n/a | |
---|
1053 | n/a | hour, minute (required) |
---|
1054 | n/a | second, microsecond (default to zero) |
---|
1055 | n/a | tzinfo (default to None) |
---|
1056 | n/a | fold (keyword only, default to zero) |
---|
1057 | n/a | """ |
---|
1058 | n/a | if isinstance(hour, bytes) and len(hour) == 6 and hour[0]&0x7F < 24: |
---|
1059 | n/a | # Pickle support |
---|
1060 | n/a | self = object.__new__(cls) |
---|
1061 | n/a | self.__setstate(hour, minute or None) |
---|
1062 | n/a | self._hashcode = -1 |
---|
1063 | n/a | return self |
---|
1064 | n/a | hour, minute, second, microsecond, fold = _check_time_fields( |
---|
1065 | n/a | hour, minute, second, microsecond, fold) |
---|
1066 | n/a | _check_tzinfo_arg(tzinfo) |
---|
1067 | n/a | self = object.__new__(cls) |
---|
1068 | n/a | self._hour = hour |
---|
1069 | n/a | self._minute = minute |
---|
1070 | n/a | self._second = second |
---|
1071 | n/a | self._microsecond = microsecond |
---|
1072 | n/a | self._tzinfo = tzinfo |
---|
1073 | n/a | self._hashcode = -1 |
---|
1074 | n/a | self._fold = fold |
---|
1075 | n/a | return self |
---|
1076 | n/a | |
---|
1077 | n/a | # Read-only field accessors |
---|
1078 | n/a | @property |
---|
1079 | n/a | def hour(self): |
---|
1080 | n/a | """hour (0-23)""" |
---|
1081 | n/a | return self._hour |
---|
1082 | n/a | |
---|
1083 | n/a | @property |
---|
1084 | n/a | def minute(self): |
---|
1085 | n/a | """minute (0-59)""" |
---|
1086 | n/a | return self._minute |
---|
1087 | n/a | |
---|
1088 | n/a | @property |
---|
1089 | n/a | def second(self): |
---|
1090 | n/a | """second (0-59)""" |
---|
1091 | n/a | return self._second |
---|
1092 | n/a | |
---|
1093 | n/a | @property |
---|
1094 | n/a | def microsecond(self): |
---|
1095 | n/a | """microsecond (0-999999)""" |
---|
1096 | n/a | return self._microsecond |
---|
1097 | n/a | |
---|
1098 | n/a | @property |
---|
1099 | n/a | def tzinfo(self): |
---|
1100 | n/a | """timezone info object""" |
---|
1101 | n/a | return self._tzinfo |
---|
1102 | n/a | |
---|
1103 | n/a | @property |
---|
1104 | n/a | def fold(self): |
---|
1105 | n/a | return self._fold |
---|
1106 | n/a | |
---|
1107 | n/a | # Standard conversions, __hash__ (and helpers) |
---|
1108 | n/a | |
---|
1109 | n/a | # Comparisons of time objects with other. |
---|
1110 | n/a | |
---|
1111 | n/a | def __eq__(self, other): |
---|
1112 | n/a | if isinstance(other, time): |
---|
1113 | n/a | return self._cmp(other, allow_mixed=True) == 0 |
---|
1114 | n/a | else: |
---|
1115 | n/a | return False |
---|
1116 | n/a | |
---|
1117 | n/a | def __le__(self, other): |
---|
1118 | n/a | if isinstance(other, time): |
---|
1119 | n/a | return self._cmp(other) <= 0 |
---|
1120 | n/a | else: |
---|
1121 | n/a | _cmperror(self, other) |
---|
1122 | n/a | |
---|
1123 | n/a | def __lt__(self, other): |
---|
1124 | n/a | if isinstance(other, time): |
---|
1125 | n/a | return self._cmp(other) < 0 |
---|
1126 | n/a | else: |
---|
1127 | n/a | _cmperror(self, other) |
---|
1128 | n/a | |
---|
1129 | n/a | def __ge__(self, other): |
---|
1130 | n/a | if isinstance(other, time): |
---|
1131 | n/a | return self._cmp(other) >= 0 |
---|
1132 | n/a | else: |
---|
1133 | n/a | _cmperror(self, other) |
---|
1134 | n/a | |
---|
1135 | n/a | def __gt__(self, other): |
---|
1136 | n/a | if isinstance(other, time): |
---|
1137 | n/a | return self._cmp(other) > 0 |
---|
1138 | n/a | else: |
---|
1139 | n/a | _cmperror(self, other) |
---|
1140 | n/a | |
---|
1141 | n/a | def _cmp(self, other, allow_mixed=False): |
---|
1142 | n/a | assert isinstance(other, time) |
---|
1143 | n/a | mytz = self._tzinfo |
---|
1144 | n/a | ottz = other._tzinfo |
---|
1145 | n/a | myoff = otoff = None |
---|
1146 | n/a | |
---|
1147 | n/a | if mytz is ottz: |
---|
1148 | n/a | base_compare = True |
---|
1149 | n/a | else: |
---|
1150 | n/a | myoff = self.utcoffset() |
---|
1151 | n/a | otoff = other.utcoffset() |
---|
1152 | n/a | base_compare = myoff == otoff |
---|
1153 | n/a | |
---|
1154 | n/a | if base_compare: |
---|
1155 | n/a | return _cmp((self._hour, self._minute, self._second, |
---|
1156 | n/a | self._microsecond), |
---|
1157 | n/a | (other._hour, other._minute, other._second, |
---|
1158 | n/a | other._microsecond)) |
---|
1159 | n/a | if myoff is None or otoff is None: |
---|
1160 | n/a | if allow_mixed: |
---|
1161 | n/a | return 2 # arbitrary non-zero value |
---|
1162 | n/a | else: |
---|
1163 | n/a | raise TypeError("cannot compare naive and aware times") |
---|
1164 | n/a | myhhmm = self._hour * 60 + self._minute - myoff//timedelta(minutes=1) |
---|
1165 | n/a | othhmm = other._hour * 60 + other._minute - otoff//timedelta(minutes=1) |
---|
1166 | n/a | return _cmp((myhhmm, self._second, self._microsecond), |
---|
1167 | n/a | (othhmm, other._second, other._microsecond)) |
---|
1168 | n/a | |
---|
1169 | n/a | def __hash__(self): |
---|
1170 | n/a | """Hash.""" |
---|
1171 | n/a | if self._hashcode == -1: |
---|
1172 | n/a | if self.fold: |
---|
1173 | n/a | t = self.replace(fold=0) |
---|
1174 | n/a | else: |
---|
1175 | n/a | t = self |
---|
1176 | n/a | tzoff = t.utcoffset() |
---|
1177 | n/a | if not tzoff: # zero or None |
---|
1178 | n/a | self._hashcode = hash(t._getstate()[0]) |
---|
1179 | n/a | else: |
---|
1180 | n/a | h, m = divmod(timedelta(hours=self.hour, minutes=self.minute) - tzoff, |
---|
1181 | n/a | timedelta(hours=1)) |
---|
1182 | n/a | assert not m % timedelta(minutes=1), "whole minute" |
---|
1183 | n/a | m //= timedelta(minutes=1) |
---|
1184 | n/a | if 0 <= h < 24: |
---|
1185 | n/a | self._hashcode = hash(time(h, m, self.second, self.microsecond)) |
---|
1186 | n/a | else: |
---|
1187 | n/a | self._hashcode = hash((h, m, self.second, self.microsecond)) |
---|
1188 | n/a | return self._hashcode |
---|
1189 | n/a | |
---|
1190 | n/a | # Conversion to string |
---|
1191 | n/a | |
---|
1192 | n/a | def _tzstr(self, sep=":"): |
---|
1193 | n/a | """Return formatted timezone offset (+xx:xx) or None.""" |
---|
1194 | n/a | off = self.utcoffset() |
---|
1195 | n/a | if off is not None: |
---|
1196 | n/a | if off.days < 0: |
---|
1197 | n/a | sign = "-" |
---|
1198 | n/a | off = -off |
---|
1199 | n/a | else: |
---|
1200 | n/a | sign = "+" |
---|
1201 | n/a | hh, mm = divmod(off, timedelta(hours=1)) |
---|
1202 | n/a | mm, ss = divmod(mm, timedelta(minutes=1)) |
---|
1203 | n/a | assert 0 <= hh < 24 |
---|
1204 | n/a | off = "%s%02d%s%02d" % (sign, hh, sep, mm) |
---|
1205 | n/a | if ss: |
---|
1206 | n/a | off += ':%02d' % ss.seconds |
---|
1207 | n/a | return off |
---|
1208 | n/a | |
---|
1209 | n/a | def __repr__(self): |
---|
1210 | n/a | """Convert to formal string, for repr().""" |
---|
1211 | n/a | if self._microsecond != 0: |
---|
1212 | n/a | s = ", %d, %d" % (self._second, self._microsecond) |
---|
1213 | n/a | elif self._second != 0: |
---|
1214 | n/a | s = ", %d" % self._second |
---|
1215 | n/a | else: |
---|
1216 | n/a | s = "" |
---|
1217 | n/a | s= "%s.%s(%d, %d%s)" % (self.__class__.__module__, |
---|
1218 | n/a | self.__class__.__qualname__, |
---|
1219 | n/a | self._hour, self._minute, s) |
---|
1220 | n/a | if self._tzinfo is not None: |
---|
1221 | n/a | assert s[-1:] == ")" |
---|
1222 | n/a | s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")" |
---|
1223 | n/a | if self._fold: |
---|
1224 | n/a | assert s[-1:] == ")" |
---|
1225 | n/a | s = s[:-1] + ", fold=1)" |
---|
1226 | n/a | return s |
---|
1227 | n/a | |
---|
1228 | n/a | def isoformat(self, timespec='auto'): |
---|
1229 | n/a | """Return the time formatted according to ISO. |
---|
1230 | n/a | |
---|
1231 | n/a | The full format is 'HH:MM:SS.mmmmmm+zz:zz'. By default, the fractional |
---|
1232 | n/a | part is omitted if self.microsecond == 0. |
---|
1233 | n/a | |
---|
1234 | n/a | The optional argument timespec specifies the number of additional |
---|
1235 | n/a | terms of the time to include. |
---|
1236 | n/a | """ |
---|
1237 | n/a | s = _format_time(self._hour, self._minute, self._second, |
---|
1238 | n/a | self._microsecond, timespec) |
---|
1239 | n/a | tz = self._tzstr() |
---|
1240 | n/a | if tz: |
---|
1241 | n/a | s += tz |
---|
1242 | n/a | return s |
---|
1243 | n/a | |
---|
1244 | n/a | __str__ = isoformat |
---|
1245 | n/a | |
---|
1246 | n/a | def strftime(self, fmt): |
---|
1247 | n/a | """Format using strftime(). The date part of the timestamp passed |
---|
1248 | n/a | to underlying strftime should not be used. |
---|
1249 | n/a | """ |
---|
1250 | n/a | # The year must be >= 1000 else Python's strftime implementation |
---|
1251 | n/a | # can raise a bogus exception. |
---|
1252 | n/a | timetuple = (1900, 1, 1, |
---|
1253 | n/a | self._hour, self._minute, self._second, |
---|
1254 | n/a | 0, 1, -1) |
---|
1255 | n/a | return _wrap_strftime(self, fmt, timetuple) |
---|
1256 | n/a | |
---|
1257 | n/a | def __format__(self, fmt): |
---|
1258 | n/a | if not isinstance(fmt, str): |
---|
1259 | n/a | raise TypeError("must be str, not %s" % type(fmt).__name__) |
---|
1260 | n/a | if len(fmt) != 0: |
---|
1261 | n/a | return self.strftime(fmt) |
---|
1262 | n/a | return str(self) |
---|
1263 | n/a | |
---|
1264 | n/a | # Timezone functions |
---|
1265 | n/a | |
---|
1266 | n/a | def utcoffset(self): |
---|
1267 | n/a | """Return the timezone offset in minutes east of UTC (negative west of |
---|
1268 | n/a | UTC).""" |
---|
1269 | n/a | if self._tzinfo is None: |
---|
1270 | n/a | return None |
---|
1271 | n/a | offset = self._tzinfo.utcoffset(None) |
---|
1272 | n/a | _check_utc_offset("utcoffset", offset) |
---|
1273 | n/a | return offset |
---|
1274 | n/a | |
---|
1275 | n/a | def tzname(self): |
---|
1276 | n/a | """Return the timezone name. |
---|
1277 | n/a | |
---|
1278 | n/a | Note that the name is 100% informational -- there's no requirement that |
---|
1279 | n/a | it mean anything in particular. For example, "GMT", "UTC", "-500", |
---|
1280 | n/a | "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies. |
---|
1281 | n/a | """ |
---|
1282 | n/a | if self._tzinfo is None: |
---|
1283 | n/a | return None |
---|
1284 | n/a | name = self._tzinfo.tzname(None) |
---|
1285 | n/a | _check_tzname(name) |
---|
1286 | n/a | return name |
---|
1287 | n/a | |
---|
1288 | n/a | def dst(self): |
---|
1289 | n/a | """Return 0 if DST is not in effect, or the DST offset (in minutes |
---|
1290 | n/a | eastward) if DST is in effect. |
---|
1291 | n/a | |
---|
1292 | n/a | This is purely informational; the DST offset has already been added to |
---|
1293 | n/a | the UTC offset returned by utcoffset() if applicable, so there's no |
---|
1294 | n/a | need to consult dst() unless you're interested in displaying the DST |
---|
1295 | n/a | info. |
---|
1296 | n/a | """ |
---|
1297 | n/a | if self._tzinfo is None: |
---|
1298 | n/a | return None |
---|
1299 | n/a | offset = self._tzinfo.dst(None) |
---|
1300 | n/a | _check_utc_offset("dst", offset) |
---|
1301 | n/a | return offset |
---|
1302 | n/a | |
---|
1303 | n/a | def replace(self, hour=None, minute=None, second=None, microsecond=None, |
---|
1304 | n/a | tzinfo=True, *, fold=None): |
---|
1305 | n/a | """Return a new time with new values for the specified fields.""" |
---|
1306 | n/a | if hour is None: |
---|
1307 | n/a | hour = self.hour |
---|
1308 | n/a | if minute is None: |
---|
1309 | n/a | minute = self.minute |
---|
1310 | n/a | if second is None: |
---|
1311 | n/a | second = self.second |
---|
1312 | n/a | if microsecond is None: |
---|
1313 | n/a | microsecond = self.microsecond |
---|
1314 | n/a | if tzinfo is True: |
---|
1315 | n/a | tzinfo = self.tzinfo |
---|
1316 | n/a | if fold is None: |
---|
1317 | n/a | fold = self._fold |
---|
1318 | n/a | return time(hour, minute, second, microsecond, tzinfo, fold=fold) |
---|
1319 | n/a | |
---|
1320 | n/a | # Pickle support. |
---|
1321 | n/a | |
---|
1322 | n/a | def _getstate(self, protocol=3): |
---|
1323 | n/a | us2, us3 = divmod(self._microsecond, 256) |
---|
1324 | n/a | us1, us2 = divmod(us2, 256) |
---|
1325 | n/a | h = self._hour |
---|
1326 | n/a | if self._fold and protocol > 3: |
---|
1327 | n/a | h += 128 |
---|
1328 | n/a | basestate = bytes([h, self._minute, self._second, |
---|
1329 | n/a | us1, us2, us3]) |
---|
1330 | n/a | if self._tzinfo is None: |
---|
1331 | n/a | return (basestate,) |
---|
1332 | n/a | else: |
---|
1333 | n/a | return (basestate, self._tzinfo) |
---|
1334 | n/a | |
---|
1335 | n/a | def __setstate(self, string, tzinfo): |
---|
1336 | n/a | if tzinfo is not None and not isinstance(tzinfo, _tzinfo_class): |
---|
1337 | n/a | raise TypeError("bad tzinfo state arg") |
---|
1338 | n/a | h, self._minute, self._second, us1, us2, us3 = string |
---|
1339 | n/a | if h > 127: |
---|
1340 | n/a | self._fold = 1 |
---|
1341 | n/a | self._hour = h - 128 |
---|
1342 | n/a | else: |
---|
1343 | n/a | self._fold = 0 |
---|
1344 | n/a | self._hour = h |
---|
1345 | n/a | self._microsecond = (((us1 << 8) | us2) << 8) | us3 |
---|
1346 | n/a | self._tzinfo = tzinfo |
---|
1347 | n/a | |
---|
1348 | n/a | def __reduce_ex__(self, protocol): |
---|
1349 | n/a | return (time, self._getstate(protocol)) |
---|
1350 | n/a | |
---|
1351 | n/a | def __reduce__(self): |
---|
1352 | n/a | return self.__reduce_ex__(2) |
---|
1353 | n/a | |
---|
1354 | n/a | _time_class = time # so functions w/ args named "time" can get at the class |
---|
1355 | n/a | |
---|
1356 | n/a | time.min = time(0, 0, 0) |
---|
1357 | n/a | time.max = time(23, 59, 59, 999999) |
---|
1358 | n/a | time.resolution = timedelta(microseconds=1) |
---|
1359 | n/a | |
---|
1360 | n/a | class datetime(date): |
---|
1361 | n/a | """datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]]) |
---|
1362 | n/a | |
---|
1363 | n/a | The year, month and day arguments are required. tzinfo may be None, or an |
---|
1364 | n/a | instance of a tzinfo subclass. The remaining arguments may be ints. |
---|
1365 | n/a | """ |
---|
1366 | n/a | __slots__ = date.__slots__ + time.__slots__ |
---|
1367 | n/a | |
---|
1368 | n/a | def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0, |
---|
1369 | n/a | microsecond=0, tzinfo=None, *, fold=0): |
---|
1370 | n/a | if isinstance(year, bytes) and len(year) == 10 and 1 <= year[2]&0x7F <= 12: |
---|
1371 | n/a | # Pickle support |
---|
1372 | n/a | self = object.__new__(cls) |
---|
1373 | n/a | self.__setstate(year, month) |
---|
1374 | n/a | self._hashcode = -1 |
---|
1375 | n/a | return self |
---|
1376 | n/a | year, month, day = _check_date_fields(year, month, day) |
---|
1377 | n/a | hour, minute, second, microsecond, fold = _check_time_fields( |
---|
1378 | n/a | hour, minute, second, microsecond, fold) |
---|
1379 | n/a | _check_tzinfo_arg(tzinfo) |
---|
1380 | n/a | self = object.__new__(cls) |
---|
1381 | n/a | self._year = year |
---|
1382 | n/a | self._month = month |
---|
1383 | n/a | self._day = day |
---|
1384 | n/a | self._hour = hour |
---|
1385 | n/a | self._minute = minute |
---|
1386 | n/a | self._second = second |
---|
1387 | n/a | self._microsecond = microsecond |
---|
1388 | n/a | self._tzinfo = tzinfo |
---|
1389 | n/a | self._hashcode = -1 |
---|
1390 | n/a | self._fold = fold |
---|
1391 | n/a | return self |
---|
1392 | n/a | |
---|
1393 | n/a | # Read-only field accessors |
---|
1394 | n/a | @property |
---|
1395 | n/a | def hour(self): |
---|
1396 | n/a | """hour (0-23)""" |
---|
1397 | n/a | return self._hour |
---|
1398 | n/a | |
---|
1399 | n/a | @property |
---|
1400 | n/a | def minute(self): |
---|
1401 | n/a | """minute (0-59)""" |
---|
1402 | n/a | return self._minute |
---|
1403 | n/a | |
---|
1404 | n/a | @property |
---|
1405 | n/a | def second(self): |
---|
1406 | n/a | """second (0-59)""" |
---|
1407 | n/a | return self._second |
---|
1408 | n/a | |
---|
1409 | n/a | @property |
---|
1410 | n/a | def microsecond(self): |
---|
1411 | n/a | """microsecond (0-999999)""" |
---|
1412 | n/a | return self._microsecond |
---|
1413 | n/a | |
---|
1414 | n/a | @property |
---|
1415 | n/a | def tzinfo(self): |
---|
1416 | n/a | """timezone info object""" |
---|
1417 | n/a | return self._tzinfo |
---|
1418 | n/a | |
---|
1419 | n/a | @property |
---|
1420 | n/a | def fold(self): |
---|
1421 | n/a | return self._fold |
---|
1422 | n/a | |
---|
1423 | n/a | @classmethod |
---|
1424 | n/a | def _fromtimestamp(cls, t, utc, tz): |
---|
1425 | n/a | """Construct a datetime from a POSIX timestamp (like time.time()). |
---|
1426 | n/a | |
---|
1427 | n/a | A timezone info object may be passed in as well. |
---|
1428 | n/a | """ |
---|
1429 | n/a | frac, t = _math.modf(t) |
---|
1430 | n/a | us = round(frac * 1e6) |
---|
1431 | n/a | if us >= 1000000: |
---|
1432 | n/a | t += 1 |
---|
1433 | n/a | us -= 1000000 |
---|
1434 | n/a | elif us < 0: |
---|
1435 | n/a | t -= 1 |
---|
1436 | n/a | us += 1000000 |
---|
1437 | n/a | |
---|
1438 | n/a | converter = _time.gmtime if utc else _time.localtime |
---|
1439 | n/a | y, m, d, hh, mm, ss, weekday, jday, dst = converter(t) |
---|
1440 | n/a | ss = min(ss, 59) # clamp out leap seconds if the platform has them |
---|
1441 | n/a | result = cls(y, m, d, hh, mm, ss, us, tz) |
---|
1442 | n/a | if tz is None: |
---|
1443 | n/a | # As of version 2015f max fold in IANA database is |
---|
1444 | n/a | # 23 hours at 1969-09-30 13:00:00 in Kwajalein. |
---|
1445 | n/a | # Let's probe 24 hours in the past to detect a transition: |
---|
1446 | n/a | max_fold_seconds = 24 * 3600 |
---|
1447 | n/a | y, m, d, hh, mm, ss = converter(t - max_fold_seconds)[:6] |
---|
1448 | n/a | probe1 = cls(y, m, d, hh, mm, ss, us, tz) |
---|
1449 | n/a | trans = result - probe1 - timedelta(0, max_fold_seconds) |
---|
1450 | n/a | if trans.days < 0: |
---|
1451 | n/a | y, m, d, hh, mm, ss = converter(t + trans // timedelta(0, 1))[:6] |
---|
1452 | n/a | probe2 = cls(y, m, d, hh, mm, ss, us, tz) |
---|
1453 | n/a | if probe2 == result: |
---|
1454 | n/a | result._fold = 1 |
---|
1455 | n/a | else: |
---|
1456 | n/a | result = tz.fromutc(result) |
---|
1457 | n/a | return result |
---|
1458 | n/a | |
---|
1459 | n/a | @classmethod |
---|
1460 | n/a | def fromtimestamp(cls, t, tz=None): |
---|
1461 | n/a | """Construct a datetime from a POSIX timestamp (like time.time()). |
---|
1462 | n/a | |
---|
1463 | n/a | A timezone info object may be passed in as well. |
---|
1464 | n/a | """ |
---|
1465 | n/a | _check_tzinfo_arg(tz) |
---|
1466 | n/a | |
---|
1467 | n/a | return cls._fromtimestamp(t, tz is not None, tz) |
---|
1468 | n/a | |
---|
1469 | n/a | @classmethod |
---|
1470 | n/a | def utcfromtimestamp(cls, t): |
---|
1471 | n/a | """Construct a naive UTC datetime from a POSIX timestamp.""" |
---|
1472 | n/a | return cls._fromtimestamp(t, True, None) |
---|
1473 | n/a | |
---|
1474 | n/a | @classmethod |
---|
1475 | n/a | def now(cls, tz=None): |
---|
1476 | n/a | "Construct a datetime from time.time() and optional time zone info." |
---|
1477 | n/a | t = _time.time() |
---|
1478 | n/a | return cls.fromtimestamp(t, tz) |
---|
1479 | n/a | |
---|
1480 | n/a | @classmethod |
---|
1481 | n/a | def utcnow(cls): |
---|
1482 | n/a | "Construct a UTC datetime from time.time()." |
---|
1483 | n/a | t = _time.time() |
---|
1484 | n/a | return cls.utcfromtimestamp(t) |
---|
1485 | n/a | |
---|
1486 | n/a | @classmethod |
---|
1487 | n/a | def combine(cls, date, time, tzinfo=True): |
---|
1488 | n/a | "Construct a datetime from a given date and a given time." |
---|
1489 | n/a | if not isinstance(date, _date_class): |
---|
1490 | n/a | raise TypeError("date argument must be a date instance") |
---|
1491 | n/a | if not isinstance(time, _time_class): |
---|
1492 | n/a | raise TypeError("time argument must be a time instance") |
---|
1493 | n/a | if tzinfo is True: |
---|
1494 | n/a | tzinfo = time.tzinfo |
---|
1495 | n/a | return cls(date.year, date.month, date.day, |
---|
1496 | n/a | time.hour, time.minute, time.second, time.microsecond, |
---|
1497 | n/a | tzinfo, fold=time.fold) |
---|
1498 | n/a | |
---|
1499 | n/a | def timetuple(self): |
---|
1500 | n/a | "Return local time tuple compatible with time.localtime()." |
---|
1501 | n/a | dst = self.dst() |
---|
1502 | n/a | if dst is None: |
---|
1503 | n/a | dst = -1 |
---|
1504 | n/a | elif dst: |
---|
1505 | n/a | dst = 1 |
---|
1506 | n/a | else: |
---|
1507 | n/a | dst = 0 |
---|
1508 | n/a | return _build_struct_time(self.year, self.month, self.day, |
---|
1509 | n/a | self.hour, self.minute, self.second, |
---|
1510 | n/a | dst) |
---|
1511 | n/a | |
---|
1512 | n/a | def _mktime(self): |
---|
1513 | n/a | """Return integer POSIX timestamp.""" |
---|
1514 | n/a | epoch = datetime(1970, 1, 1) |
---|
1515 | n/a | max_fold_seconds = 24 * 3600 |
---|
1516 | n/a | t = (self - epoch) // timedelta(0, 1) |
---|
1517 | n/a | def local(u): |
---|
1518 | n/a | y, m, d, hh, mm, ss = _time.localtime(u)[:6] |
---|
1519 | n/a | return (datetime(y, m, d, hh, mm, ss) - epoch) // timedelta(0, 1) |
---|
1520 | n/a | |
---|
1521 | n/a | # Our goal is to solve t = local(u) for u. |
---|
1522 | n/a | a = local(t) - t |
---|
1523 | n/a | u1 = t - a |
---|
1524 | n/a | t1 = local(u1) |
---|
1525 | n/a | if t1 == t: |
---|
1526 | n/a | # We found one solution, but it may not be the one we need. |
---|
1527 | n/a | # Look for an earlier solution (if `fold` is 0), or a |
---|
1528 | n/a | # later one (if `fold` is 1). |
---|
1529 | n/a | u2 = u1 + (-max_fold_seconds, max_fold_seconds)[self.fold] |
---|
1530 | n/a | b = local(u2) - u2 |
---|
1531 | n/a | if a == b: |
---|
1532 | n/a | return u1 |
---|
1533 | n/a | else: |
---|
1534 | n/a | b = t1 - u1 |
---|
1535 | n/a | assert a != b |
---|
1536 | n/a | u2 = t - b |
---|
1537 | n/a | t2 = local(u2) |
---|
1538 | n/a | if t2 == t: |
---|
1539 | n/a | return u2 |
---|
1540 | n/a | if t1 == t: |
---|
1541 | n/a | return u1 |
---|
1542 | n/a | # We have found both offsets a and b, but neither t - a nor t - b is |
---|
1543 | n/a | # a solution. This means t is in the gap. |
---|
1544 | n/a | return (max, min)[self.fold](u1, u2) |
---|
1545 | n/a | |
---|
1546 | n/a | |
---|
1547 | n/a | def timestamp(self): |
---|
1548 | n/a | "Return POSIX timestamp as float" |
---|
1549 | n/a | if self._tzinfo is None: |
---|
1550 | n/a | s = self._mktime() |
---|
1551 | n/a | return s + self.microsecond / 1e6 |
---|
1552 | n/a | else: |
---|
1553 | n/a | return (self - _EPOCH).total_seconds() |
---|
1554 | n/a | |
---|
1555 | n/a | def utctimetuple(self): |
---|
1556 | n/a | "Return UTC time tuple compatible with time.gmtime()." |
---|
1557 | n/a | offset = self.utcoffset() |
---|
1558 | n/a | if offset: |
---|
1559 | n/a | self -= offset |
---|
1560 | n/a | y, m, d = self.year, self.month, self.day |
---|
1561 | n/a | hh, mm, ss = self.hour, self.minute, self.second |
---|
1562 | n/a | return _build_struct_time(y, m, d, hh, mm, ss, 0) |
---|
1563 | n/a | |
---|
1564 | n/a | def date(self): |
---|
1565 | n/a | "Return the date part." |
---|
1566 | n/a | return date(self._year, self._month, self._day) |
---|
1567 | n/a | |
---|
1568 | n/a | def time(self): |
---|
1569 | n/a | "Return the time part, with tzinfo None." |
---|
1570 | n/a | return time(self.hour, self.minute, self.second, self.microsecond, fold=self.fold) |
---|
1571 | n/a | |
---|
1572 | n/a | def timetz(self): |
---|
1573 | n/a | "Return the time part, with same tzinfo." |
---|
1574 | n/a | return time(self.hour, self.minute, self.second, self.microsecond, |
---|
1575 | n/a | self._tzinfo, fold=self.fold) |
---|
1576 | n/a | |
---|
1577 | n/a | def replace(self, year=None, month=None, day=None, hour=None, |
---|
1578 | n/a | minute=None, second=None, microsecond=None, tzinfo=True, |
---|
1579 | n/a | *, fold=None): |
---|
1580 | n/a | """Return a new datetime with new values for the specified fields.""" |
---|
1581 | n/a | if year is None: |
---|
1582 | n/a | year = self.year |
---|
1583 | n/a | if month is None: |
---|
1584 | n/a | month = self.month |
---|
1585 | n/a | if day is None: |
---|
1586 | n/a | day = self.day |
---|
1587 | n/a | if hour is None: |
---|
1588 | n/a | hour = self.hour |
---|
1589 | n/a | if minute is None: |
---|
1590 | n/a | minute = self.minute |
---|
1591 | n/a | if second is None: |
---|
1592 | n/a | second = self.second |
---|
1593 | n/a | if microsecond is None: |
---|
1594 | n/a | microsecond = self.microsecond |
---|
1595 | n/a | if tzinfo is True: |
---|
1596 | n/a | tzinfo = self.tzinfo |
---|
1597 | n/a | if fold is None: |
---|
1598 | n/a | fold = self.fold |
---|
1599 | n/a | return datetime(year, month, day, hour, minute, second, |
---|
1600 | n/a | microsecond, tzinfo, fold=fold) |
---|
1601 | n/a | |
---|
1602 | n/a | def _local_timezone(self): |
---|
1603 | n/a | if self.tzinfo is None: |
---|
1604 | n/a | ts = self._mktime() |
---|
1605 | n/a | else: |
---|
1606 | n/a | ts = (self - _EPOCH) // timedelta(seconds=1) |
---|
1607 | n/a | localtm = _time.localtime(ts) |
---|
1608 | n/a | local = datetime(*localtm[:6]) |
---|
1609 | n/a | try: |
---|
1610 | n/a | # Extract TZ data if available |
---|
1611 | n/a | gmtoff = localtm.tm_gmtoff |
---|
1612 | n/a | zone = localtm.tm_zone |
---|
1613 | n/a | except AttributeError: |
---|
1614 | n/a | delta = local - datetime(*_time.gmtime(ts)[:6]) |
---|
1615 | n/a | zone = _time.strftime('%Z', localtm) |
---|
1616 | n/a | tz = timezone(delta, zone) |
---|
1617 | n/a | else: |
---|
1618 | n/a | tz = timezone(timedelta(seconds=gmtoff), zone) |
---|
1619 | n/a | return tz |
---|
1620 | n/a | |
---|
1621 | n/a | def astimezone(self, tz=None): |
---|
1622 | n/a | if tz is None: |
---|
1623 | n/a | tz = self._local_timezone() |
---|
1624 | n/a | elif not isinstance(tz, tzinfo): |
---|
1625 | n/a | raise TypeError("tz argument must be an instance of tzinfo") |
---|
1626 | n/a | |
---|
1627 | n/a | mytz = self.tzinfo |
---|
1628 | n/a | if mytz is None: |
---|
1629 | n/a | mytz = self._local_timezone() |
---|
1630 | n/a | |
---|
1631 | n/a | if tz is mytz: |
---|
1632 | n/a | return self |
---|
1633 | n/a | |
---|
1634 | n/a | # Convert self to UTC, and attach the new time zone object. |
---|
1635 | n/a | myoffset = mytz.utcoffset(self) |
---|
1636 | n/a | if myoffset is None: |
---|
1637 | n/a | raise ValueError("astimezone() requires an aware datetime") |
---|
1638 | n/a | utc = (self - myoffset).replace(tzinfo=tz) |
---|
1639 | n/a | |
---|
1640 | n/a | # Convert from UTC to tz's local time. |
---|
1641 | n/a | return tz.fromutc(utc) |
---|
1642 | n/a | |
---|
1643 | n/a | # Ways to produce a string. |
---|
1644 | n/a | |
---|
1645 | n/a | def ctime(self): |
---|
1646 | n/a | "Return ctime() style string." |
---|
1647 | n/a | weekday = self.toordinal() % 7 or 7 |
---|
1648 | n/a | return "%s %s %2d %02d:%02d:%02d %04d" % ( |
---|
1649 | n/a | _DAYNAMES[weekday], |
---|
1650 | n/a | _MONTHNAMES[self._month], |
---|
1651 | n/a | self._day, |
---|
1652 | n/a | self._hour, self._minute, self._second, |
---|
1653 | n/a | self._year) |
---|
1654 | n/a | |
---|
1655 | n/a | def isoformat(self, sep='T', timespec='auto'): |
---|
1656 | n/a | """Return the time formatted according to ISO. |
---|
1657 | n/a | |
---|
1658 | n/a | The full format looks like 'YYYY-MM-DD HH:MM:SS.mmmmmm'. |
---|
1659 | n/a | By default, the fractional part is omitted if self.microsecond == 0. |
---|
1660 | n/a | |
---|
1661 | n/a | If self.tzinfo is not None, the UTC offset is also attached, giving |
---|
1662 | n/a | giving a full format of 'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM'. |
---|
1663 | n/a | |
---|
1664 | n/a | Optional argument sep specifies the separator between date and |
---|
1665 | n/a | time, default 'T'. |
---|
1666 | n/a | |
---|
1667 | n/a | The optional argument timespec specifies the number of additional |
---|
1668 | n/a | terms of the time to include. |
---|
1669 | n/a | """ |
---|
1670 | n/a | s = ("%04d-%02d-%02d%c" % (self._year, self._month, self._day, sep) + |
---|
1671 | n/a | _format_time(self._hour, self._minute, self._second, |
---|
1672 | n/a | self._microsecond, timespec)) |
---|
1673 | n/a | |
---|
1674 | n/a | off = self.utcoffset() |
---|
1675 | n/a | if off is not None: |
---|
1676 | n/a | if off.days < 0: |
---|
1677 | n/a | sign = "-" |
---|
1678 | n/a | off = -off |
---|
1679 | n/a | else: |
---|
1680 | n/a | sign = "+" |
---|
1681 | n/a | hh, mm = divmod(off, timedelta(hours=1)) |
---|
1682 | n/a | mm, ss = divmod(mm, timedelta(minutes=1)) |
---|
1683 | n/a | s += "%s%02d:%02d" % (sign, hh, mm) |
---|
1684 | n/a | if ss: |
---|
1685 | n/a | assert not ss.microseconds |
---|
1686 | n/a | s += ":%02d" % ss.seconds |
---|
1687 | n/a | return s |
---|
1688 | n/a | |
---|
1689 | n/a | def __repr__(self): |
---|
1690 | n/a | """Convert to formal string, for repr().""" |
---|
1691 | n/a | L = [self._year, self._month, self._day, # These are never zero |
---|
1692 | n/a | self._hour, self._minute, self._second, self._microsecond] |
---|
1693 | n/a | if L[-1] == 0: |
---|
1694 | n/a | del L[-1] |
---|
1695 | n/a | if L[-1] == 0: |
---|
1696 | n/a | del L[-1] |
---|
1697 | n/a | s = "%s.%s(%s)" % (self.__class__.__module__, |
---|
1698 | n/a | self.__class__.__qualname__, |
---|
1699 | n/a | ", ".join(map(str, L))) |
---|
1700 | n/a | if self._tzinfo is not None: |
---|
1701 | n/a | assert s[-1:] == ")" |
---|
1702 | n/a | s = s[:-1] + ", tzinfo=%r" % self._tzinfo + ")" |
---|
1703 | n/a | if self._fold: |
---|
1704 | n/a | assert s[-1:] == ")" |
---|
1705 | n/a | s = s[:-1] + ", fold=1)" |
---|
1706 | n/a | return s |
---|
1707 | n/a | |
---|
1708 | n/a | def __str__(self): |
---|
1709 | n/a | "Convert to string, for str()." |
---|
1710 | n/a | return self.isoformat(sep=' ') |
---|
1711 | n/a | |
---|
1712 | n/a | @classmethod |
---|
1713 | n/a | def strptime(cls, date_string, format): |
---|
1714 | n/a | 'string, format -> new datetime parsed from a string (like time.strptime()).' |
---|
1715 | n/a | import _strptime |
---|
1716 | n/a | return _strptime._strptime_datetime(cls, date_string, format) |
---|
1717 | n/a | |
---|
1718 | n/a | def utcoffset(self): |
---|
1719 | n/a | """Return the timezone offset in minutes east of UTC (negative west of |
---|
1720 | n/a | UTC).""" |
---|
1721 | n/a | if self._tzinfo is None: |
---|
1722 | n/a | return None |
---|
1723 | n/a | offset = self._tzinfo.utcoffset(self) |
---|
1724 | n/a | _check_utc_offset("utcoffset", offset) |
---|
1725 | n/a | return offset |
---|
1726 | n/a | |
---|
1727 | n/a | def tzname(self): |
---|
1728 | n/a | """Return the timezone name. |
---|
1729 | n/a | |
---|
1730 | n/a | Note that the name is 100% informational -- there's no requirement that |
---|
1731 | n/a | it mean anything in particular. For example, "GMT", "UTC", "-500", |
---|
1732 | n/a | "-5:00", "EDT", "US/Eastern", "America/New York" are all valid replies. |
---|
1733 | n/a | """ |
---|
1734 | n/a | if self._tzinfo is None: |
---|
1735 | n/a | return None |
---|
1736 | n/a | name = self._tzinfo.tzname(self) |
---|
1737 | n/a | _check_tzname(name) |
---|
1738 | n/a | return name |
---|
1739 | n/a | |
---|
1740 | n/a | def dst(self): |
---|
1741 | n/a | """Return 0 if DST is not in effect, or the DST offset (in minutes |
---|
1742 | n/a | eastward) if DST is in effect. |
---|
1743 | n/a | |
---|
1744 | n/a | This is purely informational; the DST offset has already been added to |
---|
1745 | n/a | the UTC offset returned by utcoffset() if applicable, so there's no |
---|
1746 | n/a | need to consult dst() unless you're interested in displaying the DST |
---|
1747 | n/a | info. |
---|
1748 | n/a | """ |
---|
1749 | n/a | if self._tzinfo is None: |
---|
1750 | n/a | return None |
---|
1751 | n/a | offset = self._tzinfo.dst(self) |
---|
1752 | n/a | _check_utc_offset("dst", offset) |
---|
1753 | n/a | return offset |
---|
1754 | n/a | |
---|
1755 | n/a | # Comparisons of datetime objects with other. |
---|
1756 | n/a | |
---|
1757 | n/a | def __eq__(self, other): |
---|
1758 | n/a | if isinstance(other, datetime): |
---|
1759 | n/a | return self._cmp(other, allow_mixed=True) == 0 |
---|
1760 | n/a | elif not isinstance(other, date): |
---|
1761 | n/a | return NotImplemented |
---|
1762 | n/a | else: |
---|
1763 | n/a | return False |
---|
1764 | n/a | |
---|
1765 | n/a | def __le__(self, other): |
---|
1766 | n/a | if isinstance(other, datetime): |
---|
1767 | n/a | return self._cmp(other) <= 0 |
---|
1768 | n/a | elif not isinstance(other, date): |
---|
1769 | n/a | return NotImplemented |
---|
1770 | n/a | else: |
---|
1771 | n/a | _cmperror(self, other) |
---|
1772 | n/a | |
---|
1773 | n/a | def __lt__(self, other): |
---|
1774 | n/a | if isinstance(other, datetime): |
---|
1775 | n/a | return self._cmp(other) < 0 |
---|
1776 | n/a | elif not isinstance(other, date): |
---|
1777 | n/a | return NotImplemented |
---|
1778 | n/a | else: |
---|
1779 | n/a | _cmperror(self, other) |
---|
1780 | n/a | |
---|
1781 | n/a | def __ge__(self, other): |
---|
1782 | n/a | if isinstance(other, datetime): |
---|
1783 | n/a | return self._cmp(other) >= 0 |
---|
1784 | n/a | elif not isinstance(other, date): |
---|
1785 | n/a | return NotImplemented |
---|
1786 | n/a | else: |
---|
1787 | n/a | _cmperror(self, other) |
---|
1788 | n/a | |
---|
1789 | n/a | def __gt__(self, other): |
---|
1790 | n/a | if isinstance(other, datetime): |
---|
1791 | n/a | return self._cmp(other) > 0 |
---|
1792 | n/a | elif not isinstance(other, date): |
---|
1793 | n/a | return NotImplemented |
---|
1794 | n/a | else: |
---|
1795 | n/a | _cmperror(self, other) |
---|
1796 | n/a | |
---|
1797 | n/a | def _cmp(self, other, allow_mixed=False): |
---|
1798 | n/a | assert isinstance(other, datetime) |
---|
1799 | n/a | mytz = self._tzinfo |
---|
1800 | n/a | ottz = other._tzinfo |
---|
1801 | n/a | myoff = otoff = None |
---|
1802 | n/a | |
---|
1803 | n/a | if mytz is ottz: |
---|
1804 | n/a | base_compare = True |
---|
1805 | n/a | else: |
---|
1806 | n/a | myoff = self.utcoffset() |
---|
1807 | n/a | otoff = other.utcoffset() |
---|
1808 | n/a | # Assume that allow_mixed means that we are called from __eq__ |
---|
1809 | n/a | if allow_mixed: |
---|
1810 | n/a | if myoff != self.replace(fold=not self.fold).utcoffset(): |
---|
1811 | n/a | return 2 |
---|
1812 | n/a | if otoff != other.replace(fold=not other.fold).utcoffset(): |
---|
1813 | n/a | return 2 |
---|
1814 | n/a | base_compare = myoff == otoff |
---|
1815 | n/a | |
---|
1816 | n/a | if base_compare: |
---|
1817 | n/a | return _cmp((self._year, self._month, self._day, |
---|
1818 | n/a | self._hour, self._minute, self._second, |
---|
1819 | n/a | self._microsecond), |
---|
1820 | n/a | (other._year, other._month, other._day, |
---|
1821 | n/a | other._hour, other._minute, other._second, |
---|
1822 | n/a | other._microsecond)) |
---|
1823 | n/a | if myoff is None or otoff is None: |
---|
1824 | n/a | if allow_mixed: |
---|
1825 | n/a | return 2 # arbitrary non-zero value |
---|
1826 | n/a | else: |
---|
1827 | n/a | raise TypeError("cannot compare naive and aware datetimes") |
---|
1828 | n/a | # XXX What follows could be done more efficiently... |
---|
1829 | n/a | diff = self - other # this will take offsets into account |
---|
1830 | n/a | if diff.days < 0: |
---|
1831 | n/a | return -1 |
---|
1832 | n/a | return diff and 1 or 0 |
---|
1833 | n/a | |
---|
1834 | n/a | def __add__(self, other): |
---|
1835 | n/a | "Add a datetime and a timedelta." |
---|
1836 | n/a | if not isinstance(other, timedelta): |
---|
1837 | n/a | return NotImplemented |
---|
1838 | n/a | delta = timedelta(self.toordinal(), |
---|
1839 | n/a | hours=self._hour, |
---|
1840 | n/a | minutes=self._minute, |
---|
1841 | n/a | seconds=self._second, |
---|
1842 | n/a | microseconds=self._microsecond) |
---|
1843 | n/a | delta += other |
---|
1844 | n/a | hour, rem = divmod(delta.seconds, 3600) |
---|
1845 | n/a | minute, second = divmod(rem, 60) |
---|
1846 | n/a | if 0 < delta.days <= _MAXORDINAL: |
---|
1847 | n/a | return datetime.combine(date.fromordinal(delta.days), |
---|
1848 | n/a | time(hour, minute, second, |
---|
1849 | n/a | delta.microseconds, |
---|
1850 | n/a | tzinfo=self._tzinfo)) |
---|
1851 | n/a | raise OverflowError("result out of range") |
---|
1852 | n/a | |
---|
1853 | n/a | __radd__ = __add__ |
---|
1854 | n/a | |
---|
1855 | n/a | def __sub__(self, other): |
---|
1856 | n/a | "Subtract two datetimes, or a datetime and a timedelta." |
---|
1857 | n/a | if not isinstance(other, datetime): |
---|
1858 | n/a | if isinstance(other, timedelta): |
---|
1859 | n/a | return self + -other |
---|
1860 | n/a | return NotImplemented |
---|
1861 | n/a | |
---|
1862 | n/a | days1 = self.toordinal() |
---|
1863 | n/a | days2 = other.toordinal() |
---|
1864 | n/a | secs1 = self._second + self._minute * 60 + self._hour * 3600 |
---|
1865 | n/a | secs2 = other._second + other._minute * 60 + other._hour * 3600 |
---|
1866 | n/a | base = timedelta(days1 - days2, |
---|
1867 | n/a | secs1 - secs2, |
---|
1868 | n/a | self._microsecond - other._microsecond) |
---|
1869 | n/a | if self._tzinfo is other._tzinfo: |
---|
1870 | n/a | return base |
---|
1871 | n/a | myoff = self.utcoffset() |
---|
1872 | n/a | otoff = other.utcoffset() |
---|
1873 | n/a | if myoff == otoff: |
---|
1874 | n/a | return base |
---|
1875 | n/a | if myoff is None or otoff is None: |
---|
1876 | n/a | raise TypeError("cannot mix naive and timezone-aware time") |
---|
1877 | n/a | return base + otoff - myoff |
---|
1878 | n/a | |
---|
1879 | n/a | def __hash__(self): |
---|
1880 | n/a | if self._hashcode == -1: |
---|
1881 | n/a | if self.fold: |
---|
1882 | n/a | t = self.replace(fold=0) |
---|
1883 | n/a | else: |
---|
1884 | n/a | t = self |
---|
1885 | n/a | tzoff = t.utcoffset() |
---|
1886 | n/a | if tzoff is None: |
---|
1887 | n/a | self._hashcode = hash(t._getstate()[0]) |
---|
1888 | n/a | else: |
---|
1889 | n/a | days = _ymd2ord(self.year, self.month, self.day) |
---|
1890 | n/a | seconds = self.hour * 3600 + self.minute * 60 + self.second |
---|
1891 | n/a | self._hashcode = hash(timedelta(days, seconds, self.microsecond) - tzoff) |
---|
1892 | n/a | return self._hashcode |
---|
1893 | n/a | |
---|
1894 | n/a | # Pickle support. |
---|
1895 | n/a | |
---|
1896 | n/a | def _getstate(self, protocol=3): |
---|
1897 | n/a | yhi, ylo = divmod(self._year, 256) |
---|
1898 | n/a | us2, us3 = divmod(self._microsecond, 256) |
---|
1899 | n/a | us1, us2 = divmod(us2, 256) |
---|
1900 | n/a | m = self._month |
---|
1901 | n/a | if self._fold and protocol > 3: |
---|
1902 | n/a | m += 128 |
---|
1903 | n/a | basestate = bytes([yhi, ylo, m, self._day, |
---|
1904 | n/a | self._hour, self._minute, self._second, |
---|
1905 | n/a | us1, us2, us3]) |
---|
1906 | n/a | if self._tzinfo is None: |
---|
1907 | n/a | return (basestate,) |
---|
1908 | n/a | else: |
---|
1909 | n/a | return (basestate, self._tzinfo) |
---|
1910 | n/a | |
---|
1911 | n/a | def __setstate(self, string, tzinfo): |
---|
1912 | n/a | if tzinfo is not None and not isinstance(tzinfo, _tzinfo_class): |
---|
1913 | n/a | raise TypeError("bad tzinfo state arg") |
---|
1914 | n/a | (yhi, ylo, m, self._day, self._hour, |
---|
1915 | n/a | self._minute, self._second, us1, us2, us3) = string |
---|
1916 | n/a | if m > 127: |
---|
1917 | n/a | self._fold = 1 |
---|
1918 | n/a | self._month = m - 128 |
---|
1919 | n/a | else: |
---|
1920 | n/a | self._fold = 0 |
---|
1921 | n/a | self._month = m |
---|
1922 | n/a | self._year = yhi * 256 + ylo |
---|
1923 | n/a | self._microsecond = (((us1 << 8) | us2) << 8) | us3 |
---|
1924 | n/a | self._tzinfo = tzinfo |
---|
1925 | n/a | |
---|
1926 | n/a | def __reduce_ex__(self, protocol): |
---|
1927 | n/a | return (self.__class__, self._getstate(protocol)) |
---|
1928 | n/a | |
---|
1929 | n/a | def __reduce__(self): |
---|
1930 | n/a | return self.__reduce_ex__(2) |
---|
1931 | n/a | |
---|
1932 | n/a | |
---|
1933 | n/a | datetime.min = datetime(1, 1, 1) |
---|
1934 | n/a | datetime.max = datetime(9999, 12, 31, 23, 59, 59, 999999) |
---|
1935 | n/a | datetime.resolution = timedelta(microseconds=1) |
---|
1936 | n/a | |
---|
1937 | n/a | |
---|
1938 | n/a | def _isoweek1monday(year): |
---|
1939 | n/a | # Helper to calculate the day number of the Monday starting week 1 |
---|
1940 | n/a | # XXX This could be done more efficiently |
---|
1941 | n/a | THURSDAY = 3 |
---|
1942 | n/a | firstday = _ymd2ord(year, 1, 1) |
---|
1943 | n/a | firstweekday = (firstday + 6) % 7 # See weekday() above |
---|
1944 | n/a | week1monday = firstday - firstweekday |
---|
1945 | n/a | if firstweekday > THURSDAY: |
---|
1946 | n/a | week1monday += 7 |
---|
1947 | n/a | return week1monday |
---|
1948 | n/a | |
---|
1949 | n/a | class timezone(tzinfo): |
---|
1950 | n/a | __slots__ = '_offset', '_name' |
---|
1951 | n/a | |
---|
1952 | n/a | # Sentinel value to disallow None |
---|
1953 | n/a | _Omitted = object() |
---|
1954 | n/a | def __new__(cls, offset, name=_Omitted): |
---|
1955 | n/a | if not isinstance(offset, timedelta): |
---|
1956 | n/a | raise TypeError("offset must be a timedelta") |
---|
1957 | n/a | if name is cls._Omitted: |
---|
1958 | n/a | if not offset: |
---|
1959 | n/a | return cls.utc |
---|
1960 | n/a | name = None |
---|
1961 | n/a | elif not isinstance(name, str): |
---|
1962 | n/a | raise TypeError("name must be a string") |
---|
1963 | n/a | if not cls._minoffset <= offset <= cls._maxoffset: |
---|
1964 | n/a | raise ValueError("offset must be a timedelta " |
---|
1965 | n/a | "strictly between -timedelta(hours=24) and " |
---|
1966 | n/a | "timedelta(hours=24).") |
---|
1967 | n/a | if (offset.microseconds != 0 or offset.seconds % 60 != 0): |
---|
1968 | n/a | raise ValueError("offset must be a timedelta " |
---|
1969 | n/a | "representing a whole number of minutes") |
---|
1970 | n/a | return cls._create(offset, name) |
---|
1971 | n/a | |
---|
1972 | n/a | @classmethod |
---|
1973 | n/a | def _create(cls, offset, name=None): |
---|
1974 | n/a | self = tzinfo.__new__(cls) |
---|
1975 | n/a | self._offset = offset |
---|
1976 | n/a | self._name = name |
---|
1977 | n/a | return self |
---|
1978 | n/a | |
---|
1979 | n/a | def __getinitargs__(self): |
---|
1980 | n/a | """pickle support""" |
---|
1981 | n/a | if self._name is None: |
---|
1982 | n/a | return (self._offset,) |
---|
1983 | n/a | return (self._offset, self._name) |
---|
1984 | n/a | |
---|
1985 | n/a | def __eq__(self, other): |
---|
1986 | n/a | if type(other) != timezone: |
---|
1987 | n/a | return False |
---|
1988 | n/a | return self._offset == other._offset |
---|
1989 | n/a | |
---|
1990 | n/a | def __hash__(self): |
---|
1991 | n/a | return hash(self._offset) |
---|
1992 | n/a | |
---|
1993 | n/a | def __repr__(self): |
---|
1994 | n/a | """Convert to formal string, for repr(). |
---|
1995 | n/a | |
---|
1996 | n/a | >>> tz = timezone.utc |
---|
1997 | n/a | >>> repr(tz) |
---|
1998 | n/a | 'datetime.timezone.utc' |
---|
1999 | n/a | >>> tz = timezone(timedelta(hours=-5), 'EST') |
---|
2000 | n/a | >>> repr(tz) |
---|
2001 | n/a | "datetime.timezone(datetime.timedelta(-1, 68400), 'EST')" |
---|
2002 | n/a | """ |
---|
2003 | n/a | if self is self.utc: |
---|
2004 | n/a | return 'datetime.timezone.utc' |
---|
2005 | n/a | if self._name is None: |
---|
2006 | n/a | return "%s.%s(%r)" % (self.__class__.__module__, |
---|
2007 | n/a | self.__class__.__qualname__, |
---|
2008 | n/a | self._offset) |
---|
2009 | n/a | return "%s.%s(%r, %r)" % (self.__class__.__module__, |
---|
2010 | n/a | self.__class__.__qualname__, |
---|
2011 | n/a | self._offset, self._name) |
---|
2012 | n/a | |
---|
2013 | n/a | def __str__(self): |
---|
2014 | n/a | return self.tzname(None) |
---|
2015 | n/a | |
---|
2016 | n/a | def utcoffset(self, dt): |
---|
2017 | n/a | if isinstance(dt, datetime) or dt is None: |
---|
2018 | n/a | return self._offset |
---|
2019 | n/a | raise TypeError("utcoffset() argument must be a datetime instance" |
---|
2020 | n/a | " or None") |
---|
2021 | n/a | |
---|
2022 | n/a | def tzname(self, dt): |
---|
2023 | n/a | if isinstance(dt, datetime) or dt is None: |
---|
2024 | n/a | if self._name is None: |
---|
2025 | n/a | return self._name_from_offset(self._offset) |
---|
2026 | n/a | return self._name |
---|
2027 | n/a | raise TypeError("tzname() argument must be a datetime instance" |
---|
2028 | n/a | " or None") |
---|
2029 | n/a | |
---|
2030 | n/a | def dst(self, dt): |
---|
2031 | n/a | if isinstance(dt, datetime) or dt is None: |
---|
2032 | n/a | return None |
---|
2033 | n/a | raise TypeError("dst() argument must be a datetime instance" |
---|
2034 | n/a | " or None") |
---|
2035 | n/a | |
---|
2036 | n/a | def fromutc(self, dt): |
---|
2037 | n/a | if isinstance(dt, datetime): |
---|
2038 | n/a | if dt.tzinfo is not self: |
---|
2039 | n/a | raise ValueError("fromutc: dt.tzinfo " |
---|
2040 | n/a | "is not self") |
---|
2041 | n/a | return dt + self._offset |
---|
2042 | n/a | raise TypeError("fromutc() argument must be a datetime instance" |
---|
2043 | n/a | " or None") |
---|
2044 | n/a | |
---|
2045 | n/a | _maxoffset = timedelta(hours=23, minutes=59) |
---|
2046 | n/a | _minoffset = -_maxoffset |
---|
2047 | n/a | |
---|
2048 | n/a | @staticmethod |
---|
2049 | n/a | def _name_from_offset(delta): |
---|
2050 | n/a | if not delta: |
---|
2051 | n/a | return 'UTC' |
---|
2052 | n/a | if delta < timedelta(0): |
---|
2053 | n/a | sign = '-' |
---|
2054 | n/a | delta = -delta |
---|
2055 | n/a | else: |
---|
2056 | n/a | sign = '+' |
---|
2057 | n/a | hours, rest = divmod(delta, timedelta(hours=1)) |
---|
2058 | n/a | minutes = rest // timedelta(minutes=1) |
---|
2059 | n/a | return 'UTC{}{:02d}:{:02d}'.format(sign, hours, minutes) |
---|
2060 | n/a | |
---|
2061 | n/a | timezone.utc = timezone._create(timedelta(0)) |
---|
2062 | n/a | timezone.min = timezone._create(timezone._minoffset) |
---|
2063 | n/a | timezone.max = timezone._create(timezone._maxoffset) |
---|
2064 | n/a | _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) |
---|
2065 | n/a | |
---|
2066 | n/a | # Some time zone algebra. For a datetime x, let |
---|
2067 | n/a | # x.n = x stripped of its timezone -- its naive time. |
---|
2068 | n/a | # x.o = x.utcoffset(), and assuming that doesn't raise an exception or |
---|
2069 | n/a | # return None |
---|
2070 | n/a | # x.d = x.dst(), and assuming that doesn't raise an exception or |
---|
2071 | n/a | # return None |
---|
2072 | n/a | # x.s = x's standard offset, x.o - x.d |
---|
2073 | n/a | # |
---|
2074 | n/a | # Now some derived rules, where k is a duration (timedelta). |
---|
2075 | n/a | # |
---|
2076 | n/a | # 1. x.o = x.s + x.d |
---|
2077 | n/a | # This follows from the definition of x.s. |
---|
2078 | n/a | # |
---|
2079 | n/a | # 2. If x and y have the same tzinfo member, x.s = y.s. |
---|
2080 | n/a | # This is actually a requirement, an assumption we need to make about |
---|
2081 | n/a | # sane tzinfo classes. |
---|
2082 | n/a | # |
---|
2083 | n/a | # 3. The naive UTC time corresponding to x is x.n - x.o. |
---|
2084 | n/a | # This is again a requirement for a sane tzinfo class. |
---|
2085 | n/a | # |
---|
2086 | n/a | # 4. (x+k).s = x.s |
---|
2087 | n/a | # This follows from #2, and that datimetimetz+timedelta preserves tzinfo. |
---|
2088 | n/a | # |
---|
2089 | n/a | # 5. (x+k).n = x.n + k |
---|
2090 | n/a | # Again follows from how arithmetic is defined. |
---|
2091 | n/a | # |
---|
2092 | n/a | # Now we can explain tz.fromutc(x). Let's assume it's an interesting case |
---|
2093 | n/a | # (meaning that the various tzinfo methods exist, and don't blow up or return |
---|
2094 | n/a | # None when called). |
---|
2095 | n/a | # |
---|
2096 | n/a | # The function wants to return a datetime y with timezone tz, equivalent to x. |
---|
2097 | n/a | # x is already in UTC. |
---|
2098 | n/a | # |
---|
2099 | n/a | # By #3, we want |
---|
2100 | n/a | # |
---|
2101 | n/a | # y.n - y.o = x.n [1] |
---|
2102 | n/a | # |
---|
2103 | n/a | # The algorithm starts by attaching tz to x.n, and calling that y. So |
---|
2104 | n/a | # x.n = y.n at the start. Then it wants to add a duration k to y, so that [1] |
---|
2105 | n/a | # becomes true; in effect, we want to solve [2] for k: |
---|
2106 | n/a | # |
---|
2107 | n/a | # (y+k).n - (y+k).o = x.n [2] |
---|
2108 | n/a | # |
---|
2109 | n/a | # By #1, this is the same as |
---|
2110 | n/a | # |
---|
2111 | n/a | # (y+k).n - ((y+k).s + (y+k).d) = x.n [3] |
---|
2112 | n/a | # |
---|
2113 | n/a | # By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start. |
---|
2114 | n/a | # Substituting that into [3], |
---|
2115 | n/a | # |
---|
2116 | n/a | # x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving |
---|
2117 | n/a | # k - (y+k).s - (y+k).d = 0; rearranging, |
---|
2118 | n/a | # k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so |
---|
2119 | n/a | # k = y.s - (y+k).d |
---|
2120 | n/a | # |
---|
2121 | n/a | # On the RHS, (y+k).d can't be computed directly, but y.s can be, and we |
---|
2122 | n/a | # approximate k by ignoring the (y+k).d term at first. Note that k can't be |
---|
2123 | n/a | # very large, since all offset-returning methods return a duration of magnitude |
---|
2124 | n/a | # less than 24 hours. For that reason, if y is firmly in std time, (y+k).d must |
---|
2125 | n/a | # be 0, so ignoring it has no consequence then. |
---|
2126 | n/a | # |
---|
2127 | n/a | # In any case, the new value is |
---|
2128 | n/a | # |
---|
2129 | n/a | # z = y + y.s [4] |
---|
2130 | n/a | # |
---|
2131 | n/a | # It's helpful to step back at look at [4] from a higher level: it's simply |
---|
2132 | n/a | # mapping from UTC to tz's standard time. |
---|
2133 | n/a | # |
---|
2134 | n/a | # At this point, if |
---|
2135 | n/a | # |
---|
2136 | n/a | # z.n - z.o = x.n [5] |
---|
2137 | n/a | # |
---|
2138 | n/a | # we have an equivalent time, and are almost done. The insecurity here is |
---|
2139 | n/a | # at the start of daylight time. Picture US Eastern for concreteness. The wall |
---|
2140 | n/a | # time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good |
---|
2141 | n/a | # sense then. The docs ask that an Eastern tzinfo class consider such a time to |
---|
2142 | n/a | # be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST |
---|
2143 | n/a | # on the day DST starts. We want to return the 1:MM EST spelling because that's |
---|
2144 | n/a | # the only spelling that makes sense on the local wall clock. |
---|
2145 | n/a | # |
---|
2146 | n/a | # In fact, if [5] holds at this point, we do have the standard-time spelling, |
---|
2147 | n/a | # but that takes a bit of proof. We first prove a stronger result. What's the |
---|
2148 | n/a | # difference between the LHS and RHS of [5]? Let |
---|
2149 | n/a | # |
---|
2150 | n/a | # diff = x.n - (z.n - z.o) [6] |
---|
2151 | n/a | # |
---|
2152 | n/a | # Now |
---|
2153 | n/a | # z.n = by [4] |
---|
2154 | n/a | # (y + y.s).n = by #5 |
---|
2155 | n/a | # y.n + y.s = since y.n = x.n |
---|
2156 | n/a | # x.n + y.s = since z and y are have the same tzinfo member, |
---|
2157 | n/a | # y.s = z.s by #2 |
---|
2158 | n/a | # x.n + z.s |
---|
2159 | n/a | # |
---|
2160 | n/a | # Plugging that back into [6] gives |
---|
2161 | n/a | # |
---|
2162 | n/a | # diff = |
---|
2163 | n/a | # x.n - ((x.n + z.s) - z.o) = expanding |
---|
2164 | n/a | # x.n - x.n - z.s + z.o = cancelling |
---|
2165 | n/a | # - z.s + z.o = by #2 |
---|
2166 | n/a | # z.d |
---|
2167 | n/a | # |
---|
2168 | n/a | # So diff = z.d. |
---|
2169 | n/a | # |
---|
2170 | n/a | # If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time |
---|
2171 | n/a | # spelling we wanted in the endcase described above. We're done. Contrarily, |
---|
2172 | n/a | # if z.d = 0, then we have a UTC equivalent, and are also done. |
---|
2173 | n/a | # |
---|
2174 | n/a | # If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to |
---|
2175 | n/a | # add to z (in effect, z is in tz's standard time, and we need to shift the |
---|
2176 | n/a | # local clock into tz's daylight time). |
---|
2177 | n/a | # |
---|
2178 | n/a | # Let |
---|
2179 | n/a | # |
---|
2180 | n/a | # z' = z + z.d = z + diff [7] |
---|
2181 | n/a | # |
---|
2182 | n/a | # and we can again ask whether |
---|
2183 | n/a | # |
---|
2184 | n/a | # z'.n - z'.o = x.n [8] |
---|
2185 | n/a | # |
---|
2186 | n/a | # If so, we're done. If not, the tzinfo class is insane, according to the |
---|
2187 | n/a | # assumptions we've made. This also requires a bit of proof. As before, let's |
---|
2188 | n/a | # compute the difference between the LHS and RHS of [8] (and skipping some of |
---|
2189 | n/a | # the justifications for the kinds of substitutions we've done several times |
---|
2190 | n/a | # already): |
---|
2191 | n/a | # |
---|
2192 | n/a | # diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7] |
---|
2193 | n/a | # x.n - (z.n + diff - z'.o) = replacing diff via [6] |
---|
2194 | n/a | # x.n - (z.n + x.n - (z.n - z.o) - z'.o) = |
---|
2195 | n/a | # x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n |
---|
2196 | n/a | # - z.n + z.n - z.o + z'.o = cancel z.n |
---|
2197 | n/a | # - z.o + z'.o = #1 twice |
---|
2198 | n/a | # -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo |
---|
2199 | n/a | # z'.d - z.d |
---|
2200 | n/a | # |
---|
2201 | n/a | # So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal, |
---|
2202 | n/a | # we've found the UTC-equivalent so are done. In fact, we stop with [7] and |
---|
2203 | n/a | # return z', not bothering to compute z'.d. |
---|
2204 | n/a | # |
---|
2205 | n/a | # How could z.d and z'd differ? z' = z + z.d [7], so merely moving z' by |
---|
2206 | n/a | # a dst() offset, and starting *from* a time already in DST (we know z.d != 0), |
---|
2207 | n/a | # would have to change the result dst() returns: we start in DST, and moving |
---|
2208 | n/a | # a little further into it takes us out of DST. |
---|
2209 | n/a | # |
---|
2210 | n/a | # There isn't a sane case where this can happen. The closest it gets is at |
---|
2211 | n/a | # the end of DST, where there's an hour in UTC with no spelling in a hybrid |
---|
2212 | n/a | # tzinfo class. In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT. During |
---|
2213 | n/a | # that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM |
---|
2214 | n/a | # UTC) because the docs insist on that, but 0:MM is taken as being in daylight |
---|
2215 | n/a | # time (4:MM UTC). There is no local time mapping to 5:MM UTC. The local |
---|
2216 | n/a | # clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in |
---|
2217 | n/a | # standard time. Since that's what the local clock *does*, we want to map both |
---|
2218 | n/a | # UTC hours 5:MM and 6:MM to 1:MM Eastern. The result is ambiguous |
---|
2219 | n/a | # in local time, but so it goes -- it's the way the local clock works. |
---|
2220 | n/a | # |
---|
2221 | n/a | # When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0, |
---|
2222 | n/a | # so z=0:MM. z.d=60 (minutes) then, so [5] doesn't hold and we keep going. |
---|
2223 | n/a | # z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8] |
---|
2224 | n/a | # (correctly) concludes that z' is not UTC-equivalent to x. |
---|
2225 | n/a | # |
---|
2226 | n/a | # Because we know z.d said z was in daylight time (else [5] would have held and |
---|
2227 | n/a | # we would have stopped then), and we know z.d != z'.d (else [8] would have held |
---|
2228 | n/a | # and we have stopped then), and there are only 2 possible values dst() can |
---|
2229 | n/a | # return in Eastern, it follows that z'.d must be 0 (which it is in the example, |
---|
2230 | n/a | # but the reasoning doesn't depend on the example -- it depends on there being |
---|
2231 | n/a | # two possible dst() outcomes, one zero and the other non-zero). Therefore |
---|
2232 | n/a | # z' must be in standard time, and is the spelling we want in this case. |
---|
2233 | n/a | # |
---|
2234 | n/a | # Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is |
---|
2235 | n/a | # concerned (because it takes z' as being in standard time rather than the |
---|
2236 | n/a | # daylight time we intend here), but returning it gives the real-life "local |
---|
2237 | n/a | # clock repeats an hour" behavior when mapping the "unspellable" UTC hour into |
---|
2238 | n/a | # tz. |
---|
2239 | n/a | # |
---|
2240 | n/a | # When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with |
---|
2241 | n/a | # the 1:MM standard time spelling we want. |
---|
2242 | n/a | # |
---|
2243 | n/a | # So how can this break? One of the assumptions must be violated. Two |
---|
2244 | n/a | # possibilities: |
---|
2245 | n/a | # |
---|
2246 | n/a | # 1) [2] effectively says that y.s is invariant across all y belong to a given |
---|
2247 | n/a | # time zone. This isn't true if, for political reasons or continental drift, |
---|
2248 | n/a | # a region decides to change its base offset from UTC. |
---|
2249 | n/a | # |
---|
2250 | n/a | # 2) There may be versions of "double daylight" time where the tail end of |
---|
2251 | n/a | # the analysis gives up a step too early. I haven't thought about that |
---|
2252 | n/a | # enough to say. |
---|
2253 | n/a | # |
---|
2254 | n/a | # In any case, it's clear that the default fromutc() is strong enough to handle |
---|
2255 | n/a | # "almost all" time zones: so long as the standard offset is invariant, it |
---|
2256 | n/a | # doesn't matter if daylight time transition points change from year to year, or |
---|
2257 | n/a | # if daylight time is skipped in some years; it doesn't matter how large or |
---|
2258 | n/a | # small dst() may get within its bounds; and it doesn't even matter if some |
---|
2259 | n/a | # perverse time zone returns a negative dst()). So a breaking case must be |
---|
2260 | n/a | # pretty bizarre, and a tzinfo subclass can override fromutc() if it is. |
---|
2261 | n/a | |
---|
2262 | n/a | try: |
---|
2263 | n/a | from _datetime import * |
---|
2264 | n/a | except ImportError: |
---|
2265 | n/a | pass |
---|
2266 | n/a | else: |
---|
2267 | n/a | # Clean up unused names |
---|
2268 | n/a | del (_DAYNAMES, _DAYS_BEFORE_MONTH, _DAYS_IN_MONTH, _DI100Y, _DI400Y, |
---|
2269 | n/a | _DI4Y, _EPOCH, _MAXORDINAL, _MONTHNAMES, _build_struct_time, |
---|
2270 | n/a | _check_date_fields, _check_int_field, _check_time_fields, |
---|
2271 | n/a | _check_tzinfo_arg, _check_tzname, _check_utc_offset, _cmp, _cmperror, |
---|
2272 | n/a | _date_class, _days_before_month, _days_before_year, _days_in_month, |
---|
2273 | n/a | _format_time, _is_leap, _isoweek1monday, _math, _ord2ymd, |
---|
2274 | n/a | _time, _time_class, _tzinfo_class, _wrap_strftime, _ymd2ord) |
---|
2275 | n/a | # XXX Since import * above excludes names that start with _, |
---|
2276 | n/a | # docstring does not get overwritten. In the future, it may be |
---|
2277 | n/a | # appropriate to maintain a single module level docstring and |
---|
2278 | n/a | # remove the following line. |
---|
2279 | n/a | from _datetime import __doc__ |
---|