crosshair-tool 0.0.97__cp314-cp314-macosx_10_13_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of crosshair-tool might be problematic. Click here for more details.

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