Debian Codegraph @

lib-python/3/datetime.py

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