Debian Codegraph @

Lib/test/datetimetester.py

raw
1 """Test the datetime module."""
2 import bisect
3 import contextlib
4 import copy
5 import decimal
6 import io
7 import itertools
8 import os
9 import pickle
10 import random
11 import re
12 import struct
13 import sys
14 import textwrap
15 import unittest
16 import warnings
17
18 from array import array
19
20 from operator import lt, le, gt, ge, eq, ne, truediv, floordiv, mod
21
22 from test import support
23 from test.support import is_resource_enabled, ALWAYS_EQ, LARGEST, SMALLEST
24 from test.support import os_helper, script_helper, warnings_helper
25
26 import datetime as datetime_module
27 from datetime import MINYEAR, MAXYEAR
28 from datetime import timedelta
29 from datetime import tzinfo
30 from datetime import time
31 from datetime import timezone
32 from datetime import UTC
33 from datetime import date, datetime
34 import time as _time
35
36 try:
37 import _testcapi
38 except ImportError:
39 _testcapi = None
40 try:
41 import _interpreters
42 except ModuleNotFoundError:
43 _interpreters = None
44
45 # Needed by test_datetime
46 import _strptime
47 try:
48 import _pydatetime
49 except ImportError:
50 _pydatetime = None
51 try:
52 import _datetime
53 except ImportError:
54 _datetime = None
55 #
56
57 pickle_loads = {pickle.loads, pickle._loads}
58
59 pickle_choices = [(pickle, pickle, proto)
60 for proto in range(pickle.HIGHEST_PROTOCOL + 1)]
61 assert len(pickle_choices) == pickle.HIGHEST_PROTOCOL + 1
62
63 EPOCH_NAIVE = datetime(1970, 1, 1, 0, 0) # For calculating transitions
64
65 # An arbitrary collection of objects of non-datetime types, for testing
66 # mixed-type comparisons.
67 OTHERSTUFF = (10, 34.5, "abc", {}, [], ())
68
69 # XXX Copied from test_float.
70 INF = float("inf")
71 NAN = float("nan")
72
73
74 #############################################################################
75 # module tests
76
77 class TestModule(unittest.TestCase):
78
79 def test_constants(self):
80 datetime = datetime_module
81 self.assertEqual(datetime.MINYEAR, 1)
82 self.assertEqual(datetime.MAXYEAR, 9999)
83
84 def test_utc_alias(self):
85 self.assertIs(UTC, timezone.utc)
86
87 def test_all(self):
88 """Test that __all__ only points to valid attributes."""
89 all_attrs = dir(datetime_module)
90 for attr in datetime_module.__all__:
91 self.assertIn(attr, all_attrs)
92
93 def test_name_cleanup(self):
94 if '_Pure' in self.__class__.__name__:
95 self.skipTest('Only run for Fast C implementation')
96
97 datetime = datetime_module
98 names = set(name for name in dir(datetime)
99 if not name.startswith('__') and not name.endswith('__'))
100 allowed = set(['MAXYEAR', 'MINYEAR', 'date', 'datetime',
101 'datetime_CAPI', 'time', 'timedelta', 'timezone',
102 'tzinfo', 'UTC', 'sys'])
103 self.assertEqual(names - allowed, set([]))
104
105 def test_divide_and_round(self):
106 if '_Fast' in self.__class__.__name__:
107 self.skipTest('Only run for Pure Python implementation')
108
109 dar = _pydatetime._divide_and_round
110
111 self.assertEqual(dar(-10, -3), 3)
112 self.assertEqual(dar(5, -2), -2)
113
114 # four cases: (2 signs of a) x (2 signs of b)
115 self.assertEqual(dar(7, 3), 2)
116 self.assertEqual(dar(-7, 3), -2)
117 self.assertEqual(dar(7, -3), -2)
118 self.assertEqual(dar(-7, -3), 2)
119
120 # ties to even - eight cases:
121 # (2 signs of a) x (2 signs of b) x (even / odd quotient)
122 self.assertEqual(dar(10, 4), 2)
123 self.assertEqual(dar(-10, 4), -2)
124 self.assertEqual(dar(10, -4), -2)
125 self.assertEqual(dar(-10, -4), 2)
126
127 self.assertEqual(dar(6, 4), 2)
128 self.assertEqual(dar(-6, 4), -2)
129 self.assertEqual(dar(6, -4), -2)
130 self.assertEqual(dar(-6, -4), 2)
131
132
133 #############################################################################
134 # tzinfo tests
135
136 class FixedOffset(tzinfo):
137
138 def __init__(self, offset, name, dstoffset=42):
139 if isinstance(offset, int):
140 offset = timedelta(minutes=offset)
141 if isinstance(dstoffset, int):
142 dstoffset = timedelta(minutes=dstoffset)
143 self.__offset = offset
144 self.__name = name
145 self.__dstoffset = dstoffset
146 def __repr__(self):
147 return self.__name.lower()
148 def utcoffset(self, dt):
149 return self.__offset
150 def tzname(self, dt):
151 return self.__name
152 def dst(self, dt):
153 return self.__dstoffset
154
155 class PicklableFixedOffset(FixedOffset):
156
157 def __init__(self, offset=None, name=None, dstoffset=None):
158 FixedOffset.__init__(self, offset, name, dstoffset)
159
160 class PicklableFixedOffsetWithSlots(PicklableFixedOffset):
161 __slots__ = '_FixedOffset__offset', '_FixedOffset__name', 'spam'
162
163 class _TZInfo(tzinfo):
164 def utcoffset(self, datetime_module):
165 return random.random()
166
167 class TestTZInfo(unittest.TestCase):
168
169 def test_refcnt_crash_bug_22044(self):
170 tz1 = _TZInfo()
171 dt1 = datetime(2014, 7, 21, 11, 32, 3, 0, tz1)
172 with self.assertRaises(TypeError):
173 dt1.utcoffset()
174
175 def test_non_abstractness(self):
176 # In order to allow subclasses to get pickled, the C implementation
177 # wasn't able to get away with having __init__ raise
178 # NotImplementedError.
179 useless = tzinfo()
180 dt = datetime.max
181 self.assertRaises(NotImplementedError, useless.tzname, dt)
182 self.assertRaises(NotImplementedError, useless.utcoffset, dt)
183 self.assertRaises(NotImplementedError, useless.dst, dt)
184
185 def test_subclass_must_override(self):
186 class NotEnough(tzinfo):
187 def __init__(self, offset, name):
188 self.__offset = offset
189 self.__name = name
190 self.assertIsSubclass(NotEnough, tzinfo)
191 ne = NotEnough(3, "NotByALongShot")
192 self.assertIsInstance(ne, tzinfo)
193
194 dt = datetime.now()
195 self.assertRaises(NotImplementedError, ne.tzname, dt)
196 self.assertRaises(NotImplementedError, ne.utcoffset, dt)
197 self.assertRaises(NotImplementedError, ne.dst, dt)
198
199 def test_normal(self):
200 fo = FixedOffset(3, "Three")
201 self.assertIsInstance(fo, tzinfo)
202 for dt in datetime.now(), None:
203 self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3))
204 self.assertEqual(fo.tzname(dt), "Three")
205 self.assertEqual(fo.dst(dt), timedelta(minutes=42))
206
207 def test_pickling_base(self):
208 # There's no point to pickling tzinfo objects on their own (they
209 # carry no data), but they need to be picklable anyway else
210 # concrete subclasses can't be pickled.
211 orig = tzinfo.__new__(tzinfo)
212 self.assertIs(type(orig), tzinfo)
213 for pickler, unpickler, proto in pickle_choices:
214 green = pickler.dumps(orig, proto)
215 derived = unpickler.loads(green)
216 self.assertIs(type(derived), tzinfo)
217
218 def test_pickling_subclass(self):
219 # Make sure we can pickle/unpickle an instance of a subclass.
220 offset = timedelta(minutes=-300)
221 for otype, args in [
222 (PicklableFixedOffset, (offset, 'cookie')),
223 (PicklableFixedOffsetWithSlots, (offset, 'cookie')),
224 (timezone, (offset,)),
225 (timezone, (offset, "EST"))]:
226 orig = otype(*args)
227 oname = orig.tzname(None)
228 self.assertIsInstance(orig, tzinfo)
229 self.assertIs(type(orig), otype)
230 self.assertEqual(orig.utcoffset(None), offset)
231 self.assertEqual(orig.tzname(None), oname)
232 for pickler, unpickler, proto in pickle_choices:
233 green = pickler.dumps(orig, proto)
234 derived = unpickler.loads(green)
235 self.assertIsInstance(derived, tzinfo)
236 self.assertIs(type(derived), otype)
237 self.assertEqual(derived.utcoffset(None), offset)
238 self.assertEqual(derived.tzname(None), oname)
239 self.assertNotHasAttr(derived, 'spam')
240
241 def test_issue23600(self):
242 DSTDIFF = DSTOFFSET = timedelta(hours=1)
243
244 class UKSummerTime(tzinfo):
245 """Simple time zone which pretends to always be in summer time, since
246 that's what shows the failure.
247 """
248
249 def utcoffset(self, dt):
250 return DSTOFFSET
251
252 def dst(self, dt):
253 return DSTDIFF
254
255 def tzname(self, dt):
256 return 'UKSummerTime'
257
258 tz = UKSummerTime()
259 u = datetime(2014, 4, 26, 12, 1, tzinfo=tz)
260 t = tz.fromutc(u)
261 self.assertEqual(t - t.utcoffset(), u)
262
263
264 class TestTimeZone(unittest.TestCase):
265
266 def setUp(self):
267 self.ACDT = timezone(timedelta(hours=9.5), 'ACDT')
268 self.EST = timezone(-timedelta(hours=5), 'EST')
269 self.DT = datetime(2010, 1, 1)
270
271 def test_str(self):
272 for tz in [self.ACDT, self.EST, timezone.utc,
273 timezone.min, timezone.max]:
274 self.assertEqual(str(tz), tz.tzname(None))
275
276 def test_repr(self):
277 datetime = datetime_module
278 for tz in [self.ACDT, self.EST, timezone.utc,
279 timezone.min, timezone.max]:
280 # test round-trip
281 tzrep = repr(tz)
282 self.assertEqual(tz, eval(tzrep))
283
284 def test_class_members(self):
285 limit = timedelta(hours=23, minutes=59)
286 self.assertEqual(timezone.utc.utcoffset(None), ZERO)
287 self.assertEqual(timezone.min.utcoffset(None), -limit)
288 self.assertEqual(timezone.max.utcoffset(None), limit)
289
290 def test_constructor(self):
291 self.assertIs(timezone.utc, timezone(timedelta(0)))
292 self.assertIsNot(timezone.utc, timezone(timedelta(0), 'UTC'))
293 self.assertEqual(timezone.utc, timezone(timedelta(0), 'UTC'))
294 for subminute in [timedelta(microseconds=1), timedelta(seconds=1)]:
295 tz = timezone(subminute)
296 self.assertNotEqual(tz.utcoffset(None) % timedelta(minutes=1), 0)
297 # invalid offsets
298 for invalid in [timedelta(1, 1), timedelta(1)]:
299 self.assertRaises(ValueError, timezone, invalid)
300 self.assertRaises(ValueError, timezone, -invalid)
301
302 with self.assertRaises(TypeError): timezone(None)
303 with self.assertRaises(TypeError): timezone(42)
304 with self.assertRaises(TypeError): timezone(ZERO, None)
305 with self.assertRaises(TypeError): timezone(ZERO, 42)
306 with self.assertRaises(TypeError): timezone(ZERO, 'ABC', 'extra')
307
308 def test_inheritance(self):
309 self.assertIsInstance(timezone.utc, tzinfo)
310 self.assertIsInstance(self.EST, tzinfo)
311
312 def test_cannot_subclass(self):
313 with self.assertRaises(TypeError):
314 class MyTimezone(timezone): pass
315
316 def test_utcoffset(self):
317 dummy = self.DT
318 for h in [0, 1.5, 12]:
319 offset = h * HOUR
320 self.assertEqual(offset, timezone(offset).utcoffset(dummy))
321 self.assertEqual(-offset, timezone(-offset).utcoffset(dummy))
322
323 with self.assertRaises(TypeError): self.EST.utcoffset('')
324 with self.assertRaises(TypeError): self.EST.utcoffset(5)
325
326
327 def test_dst(self):
328 self.assertIsNone(timezone.utc.dst(self.DT))
329
330 with self.assertRaises(TypeError): self.EST.dst('')
331 with self.assertRaises(TypeError): self.EST.dst(5)
332
333 def test_tzname(self):
334 self.assertEqual('UTC', timezone.utc.tzname(None))
335 self.assertEqual('UTC', UTC.tzname(None))
336 self.assertEqual('UTC', timezone(ZERO).tzname(None))
337 self.assertEqual('UTC-05:00', timezone(-5 * HOUR).tzname(None))
338 self.assertEqual('UTC+09:30', timezone(9.5 * HOUR).tzname(None))
339 self.assertEqual('UTC-00:01', timezone(timedelta(minutes=-1)).tzname(None))
340 self.assertEqual('XYZ', timezone(-5 * HOUR, 'XYZ').tzname(None))
341 # bpo-34482: Check that surrogates are handled properly.
342 self.assertEqual('\ud800', timezone(ZERO, '\ud800').tzname(None))
343
344 # Sub-minute offsets:
345 self.assertEqual('UTC+01:06:40', timezone(timedelta(0, 4000)).tzname(None))
346 self.assertEqual('UTC-01:06:40',
347 timezone(-timedelta(0, 4000)).tzname(None))
348 self.assertEqual('UTC+01:06:40.000001',
349 timezone(timedelta(0, 4000, 1)).tzname(None))
350 self.assertEqual('UTC-01:06:40.000001',
351 timezone(-timedelta(0, 4000, 1)).tzname(None))
352
353 with self.assertRaises(TypeError): self.EST.tzname('')
354 with self.assertRaises(TypeError): self.EST.tzname(5)
355
356 def test_fromutc(self):
357 with self.assertRaises(ValueError):
358 timezone.utc.fromutc(self.DT)
359 with self.assertRaises(TypeError):
360 timezone.utc.fromutc('not datetime')
361 for tz in [self.EST, self.ACDT, Eastern]:
362 utctime = self.DT.replace(tzinfo=tz)
363 local = tz.fromutc(utctime)
364 self.assertEqual(local - utctime, tz.utcoffset(local))
365 self.assertEqual(local,
366 self.DT.replace(tzinfo=timezone.utc))
367
368 def test_comparison(self):
369 self.assertNotEqual(timezone(ZERO), timezone(HOUR))
370 self.assertEqual(timezone(HOUR), timezone(HOUR))
371 self.assertEqual(timezone(-5 * HOUR), timezone(-5 * HOUR, 'EST'))
372 with self.assertRaises(TypeError): timezone(ZERO) < timezone(ZERO)
373 self.assertIn(timezone(ZERO), {timezone(ZERO)})
374 self.assertTrue(timezone(ZERO) != None)
375 self.assertFalse(timezone(ZERO) == None)
376
377 tz = timezone(ZERO)
378 self.assertTrue(tz == ALWAYS_EQ)
379 self.assertFalse(tz != ALWAYS_EQ)
380 self.assertTrue(tz < LARGEST)
381 self.assertFalse(tz > LARGEST)
382 self.assertTrue(tz <= LARGEST)
383 self.assertFalse(tz >= LARGEST)
384 self.assertFalse(tz < SMALLEST)
385 self.assertTrue(tz > SMALLEST)
386 self.assertFalse(tz <= SMALLEST)
387 self.assertTrue(tz >= SMALLEST)
388
389 def test_aware_datetime(self):
390 # test that timezone instances can be used by datetime
391 t = datetime(1, 1, 1)
392 for tz in [timezone.min, timezone.max, timezone.utc]:
393 self.assertEqual(tz.tzname(t),
394 t.replace(tzinfo=tz).tzname())
395 self.assertEqual(tz.utcoffset(t),
396 t.replace(tzinfo=tz).utcoffset())
397 self.assertEqual(tz.dst(t),
398 t.replace(tzinfo=tz).dst())
399
400 def test_pickle(self):
401 for tz in self.ACDT, self.EST, timezone.min, timezone.max:
402 for pickler, unpickler, proto in pickle_choices:
403 tz_copy = unpickler.loads(pickler.dumps(tz, proto))
404 self.assertEqual(tz_copy, tz)
405 tz = timezone.utc
406 for pickler, unpickler, proto in pickle_choices:
407 tz_copy = unpickler.loads(pickler.dumps(tz, proto))
408 self.assertIs(tz_copy, tz)
409
410 def test_copy(self):
411 for tz in self.ACDT, self.EST, timezone.min, timezone.max:
412 tz_copy = copy.copy(tz)
413 self.assertEqual(tz_copy, tz)
414 tz = timezone.utc
415 tz_copy = copy.copy(tz)
416 self.assertIs(tz_copy, tz)
417
418 def test_deepcopy(self):
419 for tz in self.ACDT, self.EST, timezone.min, timezone.max:
420 tz_copy = copy.deepcopy(tz)
421 self.assertEqual(tz_copy, tz)
422 tz = timezone.utc
423 tz_copy = copy.deepcopy(tz)
424 self.assertIs(tz_copy, tz)
425
426 def test_offset_boundaries(self):
427 # Test timedeltas close to the boundaries
428 time_deltas = [
429 timedelta(hours=23, minutes=59),
430 timedelta(hours=23, minutes=59, seconds=59),
431 timedelta(hours=23, minutes=59, seconds=59, microseconds=999999),
432 ]
433 time_deltas.extend([-delta for delta in time_deltas])
434
435 for delta in time_deltas:
436 with self.subTest(test_type='good', delta=delta):
437 timezone(delta)
438
439 # Test timedeltas on and outside the boundaries
440 bad_time_deltas = [
441 timedelta(hours=24),
442 timedelta(hours=24, microseconds=1),
443 ]
444 bad_time_deltas.extend([-delta for delta in bad_time_deltas])
445
446 for delta in bad_time_deltas:
447 with self.subTest(test_type='bad', delta=delta):
448 with self.assertRaises(ValueError):
449 timezone(delta)
450
451 def test_comparison_with_tzinfo(self):
452 # Constructing tzinfo objects directly should not be done by users
453 # and serves only to check the bug described in bpo-37915
454 self.assertNotEqual(timezone.utc, tzinfo())
455 self.assertNotEqual(timezone(timedelta(hours=1)), tzinfo())
456
457 #############################################################################
458 # Base class for testing a particular aspect of timedelta, time, date and
459 # datetime comparisons.
460
461 class HarmlessMixedComparison:
462 # Test that __eq__ and __ne__ don't complain for mixed-type comparisons.
463
464 # Subclasses must define 'theclass', and theclass(1, 1, 1) must be a
465 # legit constructor.
466
467 def test_harmless_mixed_comparison(self):
468 me = self.theclass(1, 1, 1)
469
470 self.assertFalse(me == ())
471 self.assertTrue(me != ())
472 self.assertFalse(() == me)
473 self.assertTrue(() != me)
474
475 self.assertIn(me, [1, 20, [], me])
476 self.assertIn([], [me, 1, 20, []])
477
478 # Comparison to objects of unsupported types should return
479 # NotImplemented which falls back to the right hand side's __eq__
480 # method. In this case, ALWAYS_EQ.__eq__ always returns True.
481 # ALWAYS_EQ.__ne__ always returns False.
482 self.assertTrue(me == ALWAYS_EQ)
483 self.assertFalse(me != ALWAYS_EQ)
484
485 # If the other class explicitly defines ordering
486 # relative to our class, it is allowed to do so
487 self.assertTrue(me < LARGEST)
488 self.assertFalse(me > LARGEST)
489 self.assertTrue(me <= LARGEST)
490 self.assertFalse(me >= LARGEST)
491 self.assertFalse(me < SMALLEST)
492 self.assertTrue(me > SMALLEST)
493 self.assertFalse(me <= SMALLEST)
494 self.assertTrue(me >= SMALLEST)
495
496 def test_harmful_mixed_comparison(self):
497 me = self.theclass(1, 1, 1)
498
499 self.assertRaises(TypeError, lambda: me < ())
500 self.assertRaises(TypeError, lambda: me <= ())
501 self.assertRaises(TypeError, lambda: me > ())
502 self.assertRaises(TypeError, lambda: me >= ())
503
504 self.assertRaises(TypeError, lambda: () < me)
505 self.assertRaises(TypeError, lambda: () <= me)
506 self.assertRaises(TypeError, lambda: () > me)
507 self.assertRaises(TypeError, lambda: () >= me)
508
509 #############################################################################
510 # timedelta tests
511
512 class SubclassTimeDelta(timedelta):
513 sub_var = 1
514
515 class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
516
517 theclass = timedelta
518
519 def test_constructor(self):
520 eq = self.assertEqual
521 ra = self.assertRaises
522 td = timedelta
523
524 # Check keyword args to constructor
525 eq(td(), td(weeks=0, days=0, hours=0, minutes=0, seconds=0,
526 milliseconds=0, microseconds=0))
527 eq(td(1), td(days=1))
528 eq(td(0, 1), td(seconds=1))
529 eq(td(0, 0, 1), td(microseconds=1))
530 eq(td(weeks=1), td(days=7))
531 eq(td(days=1), td(hours=24))
532 eq(td(hours=1), td(minutes=60))
533 eq(td(minutes=1), td(seconds=60))
534 eq(td(seconds=1), td(milliseconds=1000))
535 eq(td(milliseconds=1), td(microseconds=1000))
536
537 # Check float args to constructor
538 eq(td(weeks=1.0/7), td(days=1))
539 eq(td(days=1.0/24), td(hours=1))
540 eq(td(hours=1.0/60), td(minutes=1))
541 eq(td(minutes=1.0/60), td(seconds=1))
542 eq(td(seconds=0.001), td(milliseconds=1))
543 eq(td(milliseconds=0.001), td(microseconds=1))
544
545 # Check type of args to constructor
546 ra(TypeError, lambda: td(weeks='1'))
547 ra(TypeError, lambda: td(days='1'))
548 ra(TypeError, lambda: td(hours='1'))
549 ra(TypeError, lambda: td(minutes='1'))
550 ra(TypeError, lambda: td(seconds='1'))
551 ra(TypeError, lambda: td(milliseconds='1'))
552 ra(TypeError, lambda: td(microseconds='1'))
553
554 def test_computations(self):
555 eq = self.assertEqual
556 td = timedelta
557
558 a = td(7) # One week
559 b = td(0, 60) # One minute
560 c = td(0, 0, 1000) # One millisecond
561 eq(a+b+c, td(7, 60, 1000))
562 eq(a-b, td(6, 24*3600 - 60))
563 eq(b.__rsub__(a), td(6, 24*3600 - 60))
564 eq(-a, td(-7))
565 eq(+a, td(7))
566 eq(-b, td(-1, 24*3600 - 60))
567 eq(-c, td(-1, 24*3600 - 1, 999000))
568 eq(abs(a), a)
569 eq(abs(-a), a)
570 eq(td(6, 24*3600), a)
571 eq(td(0, 0, 60*1000000), b)
572 eq(a*10, td(70))
573 eq(a*10, 10*a)
574 eq(a*10, 10*a)
575 eq(b*10, td(0, 600))
576 eq(10*b, td(0, 600))
577 eq(b*10, td(0, 600))
578 eq(c*10, td(0, 0, 10000))
579 eq(10*c, td(0, 0, 10000))
580 eq(c*10, td(0, 0, 10000))
581 eq(a*-1, -a)
582 eq(b*-2, -b-b)
583 eq(c*-2, -c+-c)
584 eq(b*(60*24), (b*60)*24)
585 eq(b*(60*24), (60*b)*24)
586 eq(c*1000, td(0, 1))
587 eq(1000*c, td(0, 1))
588 eq(a//7, td(1))
589 eq(b//10, td(0, 6))
590 eq(c//1000, td(0, 0, 1))
591 eq(a//10, td(0, 7*24*360))
592 eq(a//3600000, td(0, 0, 7*24*1000))
593 eq(a/0.5, td(14))
594 eq(b/0.5, td(0, 120))
595 eq(a/7, td(1))
596 eq(b/10, td(0, 6))
597 eq(c/1000, td(0, 0, 1))
598 eq(a/10, td(0, 7*24*360))
599 eq(a/3600000, td(0, 0, 7*24*1000))
600
601 # Multiplication by float
602 us = td(microseconds=1)
603 eq((3*us) * 0.5, 2*us)
604 eq((5*us) * 0.5, 2*us)
605 eq(0.5 * (3*us), 2*us)
606 eq(0.5 * (5*us), 2*us)
607 eq((-3*us) * 0.5, -2*us)
608 eq((-5*us) * 0.5, -2*us)
609
610 # Issue #23521
611 eq(td(seconds=1) * 0.123456, td(microseconds=123456))
612 eq(td(seconds=1) * 0.6112295, td(microseconds=611229))
613
614 # Division by int and float
615 eq((3*us) / 2, 2*us)
616 eq((5*us) / 2, 2*us)
617 eq((-3*us) / 2.0, -2*us)
618 eq((-5*us) / 2.0, -2*us)
619 eq((3*us) / -2, -2*us)
620 eq((5*us) / -2, -2*us)
621 eq((3*us) / -2.0, -2*us)
622 eq((5*us) / -2.0, -2*us)
623 for i in range(-10, 10):
624 eq((i*us/3)//us, round(i/3))
625 for i in range(-10, 10):
626 eq((i*us/-3)//us, round(i/-3))
627
628 # Issue #23521
629 eq(td(seconds=1) / (1 / 0.6112295), td(microseconds=611229))
630
631 # Issue #11576
632 eq(td(999999999, 86399, 999999) - td(999999999, 86399, 999998),
633 td(0, 0, 1))
634 eq(td(999999999, 1, 1) - td(999999999, 1, 0),
635 td(0, 0, 1))
636
637 def test_disallowed_computations(self):
638 a = timedelta(42)
639
640 # Add/sub ints or floats should be illegal
641 for i in 1, 1.0:
642 self.assertRaises(TypeError, lambda: a+i)
643 self.assertRaises(TypeError, lambda: a-i)
644 self.assertRaises(TypeError, lambda: i+a)
645 self.assertRaises(TypeError, lambda: i-a)
646
647 # Division of int by timedelta doesn't make sense.
648 # Division by zero doesn't make sense.
649 zero = 0
650 self.assertRaises(TypeError, lambda: zero // a)
651 self.assertRaises(ZeroDivisionError, lambda: a // zero)
652 self.assertRaises(ZeroDivisionError, lambda: a / zero)
653 self.assertRaises(ZeroDivisionError, lambda: a / 0.0)
654 self.assertRaises(TypeError, lambda: a / '')
655
656 @support.requires_IEEE_754
657 def test_disallowed_special(self):
658 a = timedelta(42)
659 self.assertRaises(ValueError, a.__mul__, NAN)
660 self.assertRaises(ValueError, a.__truediv__, NAN)
661
662 def test_basic_attributes(self):
663 days, seconds, us = 1, 7, 31
664 td = timedelta(days, seconds, us)
665 self.assertEqual(td.days, days)
666 self.assertEqual(td.seconds, seconds)
667 self.assertEqual(td.microseconds, us)
668
669 def test_total_seconds(self):
670 td = timedelta(days=365)
671 self.assertEqual(td.total_seconds(), 31536000.0)
672 for total_seconds in [123456.789012, -123456.789012, 0.123456, 0, 1e6]:
673 td = timedelta(seconds=total_seconds)
674 self.assertEqual(td.total_seconds(), total_seconds)
675 # Issue8644: Test that td.total_seconds() has the same
676 # accuracy as td / timedelta(seconds=1).
677 for ms in [-1, -2, -123]:
678 td = timedelta(microseconds=ms)
679 self.assertEqual(td.total_seconds(), td / timedelta(seconds=1))
680
681 def test_carries(self):
682 t1 = timedelta(days=100,
683 weeks=-7,
684 hours=-24*(100-49),
685 minutes=-3,
686 seconds=12,
687 microseconds=(3*60 - 12) * 1e6 + 1)
688 t2 = timedelta(microseconds=1)
689 self.assertEqual(t1, t2)
690
691 def test_hash_equality(self):
692 t1 = timedelta(days=100,
693 weeks=-7,
694 hours=-24*(100-49),
695 minutes=-3,
696 seconds=12,
697 microseconds=(3*60 - 12) * 1000000)
698 t2 = timedelta()
699 self.assertEqual(hash(t1), hash(t2))
700
701 t1 += timedelta(weeks=7)
702 t2 += timedelta(days=7*7)
703 self.assertEqual(t1, t2)
704 self.assertEqual(hash(t1), hash(t2))
705
706 d = {t1: 1}
707 d[t2] = 2
708 self.assertEqual(len(d), 1)
709 self.assertEqual(d[t1], 2)
710
711 def test_pickling(self):
712 args = 12, 34, 56
713 orig = timedelta(*args)
714 for pickler, unpickler, proto in pickle_choices:
715 green = pickler.dumps(orig, proto)
716 derived = unpickler.loads(green)
717 self.assertEqual(orig, derived)
718
719 def test_compare(self):
720 t1 = timedelta(2, 3, 4)
721 t2 = timedelta(2, 3, 4)
722 self.assertEqual(t1, t2)
723 self.assertTrue(t1 <= t2)
724 self.assertTrue(t1 >= t2)
725 self.assertFalse(t1 != t2)
726 self.assertFalse(t1 < t2)
727 self.assertFalse(t1 > t2)
728
729 for args in (3, 3, 3), (2, 4, 4), (2, 3, 5):
730 t2 = timedelta(*args) # this is larger than t1
731 self.assertTrue(t1 < t2)
732 self.assertTrue(t2 > t1)
733 self.assertTrue(t1 <= t2)
734 self.assertTrue(t2 >= t1)
735 self.assertTrue(t1 != t2)
736 self.assertTrue(t2 != t1)
737 self.assertFalse(t1 == t2)
738 self.assertFalse(t2 == t1)
739 self.assertFalse(t1 > t2)
740 self.assertFalse(t2 < t1)
741 self.assertFalse(t1 >= t2)
742 self.assertFalse(t2 <= t1)
743
744 for badarg in OTHERSTUFF:
745 self.assertEqual(t1 == badarg, False)
746 self.assertEqual(t1 != badarg, True)
747 self.assertEqual(badarg == t1, False)
748 self.assertEqual(badarg != t1, True)
749
750 self.assertRaises(TypeError, lambda: t1 <= badarg)
751 self.assertRaises(TypeError, lambda: t1 < badarg)
752 self.assertRaises(TypeError, lambda: t1 > badarg)
753 self.assertRaises(TypeError, lambda: t1 >= badarg)
754 self.assertRaises(TypeError, lambda: badarg <= t1)
755 self.assertRaises(TypeError, lambda: badarg < t1)
756 self.assertRaises(TypeError, lambda: badarg > t1)
757 self.assertRaises(TypeError, lambda: badarg >= t1)
758
759 def test_str(self):
760 td = timedelta
761 eq = self.assertEqual
762
763 eq(str(td(1)), "1 day, 0:00:00")
764 eq(str(td(-1)), "-1 day, 0:00:00")
765 eq(str(td(2)), "2 days, 0:00:00")
766 eq(str(td(-2)), "-2 days, 0:00:00")
767
768 eq(str(td(hours=12, minutes=58, seconds=59)), "12:58:59")
769 eq(str(td(hours=2, minutes=3, seconds=4)), "2:03:04")
770 eq(str(td(weeks=-30, hours=23, minutes=12, seconds=34)),
771 "-210 days, 23:12:34")
772
773 eq(str(td(milliseconds=1)), "0:00:00.001000")
774 eq(str(td(microseconds=3)), "0:00:00.000003")
775
776 eq(str(td(days=999999999, hours=23, minutes=59, seconds=59,
777 microseconds=999999)),
778 "999999999 days, 23:59:59.999999")
779
780 # test the Doc/library/datetime.rst recipe
781 eq(f'-({-td(hours=-1)!s})', "-(1:00:00)")
782
783 def test_repr(self):
784 name = 'datetime.' + self.theclass.__name__
785 self.assertEqual(repr(self.theclass(1)),
786 "%s(days=1)" % name)
787 self.assertEqual(repr(self.theclass(10, 2)),
788 "%s(days=10, seconds=2)" % name)
789 self.assertEqual(repr(self.theclass(-10, 2, 400000)),
790 "%s(days=-10, seconds=2, microseconds=400000)" % name)
791 self.assertEqual(repr(self.theclass(seconds=60)),
792 "%s(seconds=60)" % name)
793 self.assertEqual(repr(self.theclass()),
794 "%s(0)" % name)
795 self.assertEqual(repr(self.theclass(microseconds=100)),
796 "%s(microseconds=100)" % name)
797 self.assertEqual(repr(self.theclass(days=1, microseconds=100)),
798 "%s(days=1, microseconds=100)" % name)
799 self.assertEqual(repr(self.theclass(seconds=1, microseconds=100)),
800 "%s(seconds=1, microseconds=100)" % name)
801
802 def test_repr_subclass(self):
803 """Subclasses should have bare names in the repr (gh-107773)."""
804 td = SubclassTimeDelta(days=1)
805 self.assertEqual(repr(td), "SubclassTimeDelta(days=1)")
806 td = SubclassTimeDelta(seconds=30)
807 self.assertEqual(repr(td), "SubclassTimeDelta(seconds=30)")
808 td = SubclassTimeDelta(weeks=2)
809 self.assertEqual(repr(td), "SubclassTimeDelta(days=14)")
810
811 def test_roundtrip(self):
812 for td in (timedelta(days=999999999, hours=23, minutes=59,
813 seconds=59, microseconds=999999),
814 timedelta(days=-999999999),
815 timedelta(days=-999999999, seconds=1),
816 timedelta(days=1, seconds=2, microseconds=3)):
817
818 # Verify td -> string -> td identity.
819 s = repr(td)
820 self.assertStartsWith(s, 'datetime.')
821 s = s[9:]
822 td2 = eval(s)
823 self.assertEqual(td, td2)
824
825 # Verify identity via reconstructing from pieces.
826 td2 = timedelta(td.days, td.seconds, td.microseconds)
827 self.assertEqual(td, td2)
828
829 def test_resolution_info(self):
830 self.assertIsInstance(timedelta.min, timedelta)
831 self.assertIsInstance(timedelta.max, timedelta)
832 self.assertIsInstance(timedelta.resolution, timedelta)
833 self.assertTrue(timedelta.max > timedelta.min)
834 self.assertEqual(timedelta.min, timedelta(-999999999))
835 self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1))
836 self.assertEqual(timedelta.resolution, timedelta(0, 0, 1))
837
838 def test_overflow(self):
839 tiny = timedelta.resolution
840
841 td = timedelta.min + tiny
842 td -= tiny # no problem
843 self.assertRaises(OverflowError, td.__sub__, tiny)
844 self.assertRaises(OverflowError, td.__add__, -tiny)
845
846 td = timedelta.max - tiny
847 td += tiny # no problem
848 self.assertRaises(OverflowError, td.__add__, tiny)
849 self.assertRaises(OverflowError, td.__sub__, -tiny)
850
851 self.assertRaises(OverflowError, lambda: -timedelta.max)
852
853 day = timedelta(1)
854 self.assertRaises(OverflowError, day.__mul__, 10**9)
855 self.assertRaises(OverflowError, day.__mul__, 1e9)
856 self.assertRaises(OverflowError, day.__truediv__, 1e-20)
857 self.assertRaises(OverflowError, day.__truediv__, 1e-10)
858 self.assertRaises(OverflowError, day.__truediv__, 9e-10)
859
860 @support.requires_IEEE_754
861 def _test_overflow_special(self):
862 day = timedelta(1)
863 self.assertRaises(OverflowError, day.__mul__, INF)
864 self.assertRaises(OverflowError, day.__mul__, -INF)
865
866 def test_microsecond_rounding(self):
867 td = timedelta
868 eq = self.assertEqual
869
870 # Single-field rounding.
871 eq(td(milliseconds=0.4/1000), td(0)) # rounds to 0
872 eq(td(milliseconds=-0.4/1000), td(0)) # rounds to 0
873 eq(td(milliseconds=0.5/1000), td(microseconds=0))
874 eq(td(milliseconds=-0.5/1000), td(microseconds=-0))
875 eq(td(milliseconds=0.6/1000), td(microseconds=1))
876 eq(td(milliseconds=-0.6/1000), td(microseconds=-1))
877 eq(td(milliseconds=1.5/1000), td(microseconds=2))
878 eq(td(milliseconds=-1.5/1000), td(microseconds=-2))
879 eq(td(seconds=0.5/10**6), td(microseconds=0))
880 eq(td(seconds=-0.5/10**6), td(microseconds=-0))
881 eq(td(seconds=1/2**7), td(microseconds=7812))
882 eq(td(seconds=-1/2**7), td(microseconds=-7812))
883
884 # Rounding due to contributions from more than one field.
885 us_per_hour = 3600e6
886 us_per_day = us_per_hour * 24
887 eq(td(days=.4/us_per_day), td(0))
888 eq(td(hours=.2/us_per_hour), td(0))
889 eq(td(days=.4/us_per_day, hours=.2/us_per_hour), td(microseconds=1))
890
891 eq(td(days=-.4/us_per_day), td(0))
892 eq(td(hours=-.2/us_per_hour), td(0))
893 eq(td(days=-.4/us_per_day, hours=-.2/us_per_hour), td(microseconds=-1))
894
895 # Test for a patch in Issue 8860
896 eq(td(microseconds=0.5), 0.5*td(microseconds=1.0))
897 eq(td(microseconds=0.5)//td.resolution, 0.5*td.resolution//td.resolution)
898
899 def test_massive_normalization(self):
900 td = timedelta(microseconds=-1)
901 self.assertEqual((td.days, td.seconds, td.microseconds),
902 (-1, 24*3600-1, 999999))
903
904 def test_bool(self):
905 self.assertTrue(timedelta(1))
906 self.assertTrue(timedelta(0, 1))
907 self.assertTrue(timedelta(0, 0, 1))
908 self.assertTrue(timedelta(microseconds=1))
909 self.assertFalse(timedelta(0))
910
911 def test_subclass_timedelta(self):
912
913 class T(timedelta):
914 @staticmethod
915 def from_td(td):
916 return T(td.days, td.seconds, td.microseconds)
917
918 def as_hours(self):
919 sum = (self.days * 24 +
920 self.seconds / 3600.0 +
921 self.microseconds / 3600e6)
922 return round(sum)
923
924 t1 = T(days=1)
925 self.assertIs(type(t1), T)
926 self.assertEqual(t1.as_hours(), 24)
927
928 t2 = T(days=-1, seconds=-3600)
929 self.assertIs(type(t2), T)
930 self.assertEqual(t2.as_hours(), -25)
931
932 t3 = t1 + t2
933 self.assertIs(type(t3), timedelta)
934 t4 = T.from_td(t3)
935 self.assertIs(type(t4), T)
936 self.assertEqual(t3.days, t4.days)
937 self.assertEqual(t3.seconds, t4.seconds)
938 self.assertEqual(t3.microseconds, t4.microseconds)
939 self.assertEqual(str(t3), str(t4))
940 self.assertEqual(t4.as_hours(), -1)
941
942 def test_subclass_date(self):
943 class DateSubclass(date):
944 pass
945
946 d1 = DateSubclass(2018, 1, 5)
947 td = timedelta(days=1)
948
949 tests = [
950 ('add', lambda d, t: d + t, DateSubclass(2018, 1, 6)),
951 ('radd', lambda d, t: t + d, DateSubclass(2018, 1, 6)),
952 ('sub', lambda d, t: d - t, DateSubclass(2018, 1, 4)),
953 ]
954
955 for name, func, expected in tests:
956 with self.subTest(name):
957 act = func(d1, td)
958 self.assertEqual(act, expected)
959 self.assertIsInstance(act, DateSubclass)
960
961 def test_subclass_datetime(self):
962 class DateTimeSubclass(datetime):
963 pass
964
965 d1 = DateTimeSubclass(2018, 1, 5, 12, 30)
966 td = timedelta(days=1, minutes=30)
967
968 tests = [
969 ('add', lambda d, t: d + t, DateTimeSubclass(2018, 1, 6, 13)),
970 ('radd', lambda d, t: t + d, DateTimeSubclass(2018, 1, 6, 13)),
971 ('sub', lambda d, t: d - t, DateTimeSubclass(2018, 1, 4, 12)),
972 ]
973
974 for name, func, expected in tests:
975 with self.subTest(name):
976 act = func(d1, td)
977 self.assertEqual(act, expected)
978 self.assertIsInstance(act, DateTimeSubclass)
979
980 def test_division(self):
981 t = timedelta(hours=1, minutes=24, seconds=19)
982 second = timedelta(seconds=1)
983 self.assertEqual(t / second, 5059.0)
984 self.assertEqual(t // second, 5059)
985
986 t = timedelta(minutes=2, seconds=30)
987 minute = timedelta(minutes=1)
988 self.assertEqual(t / minute, 2.5)
989 self.assertEqual(t // minute, 2)
990
991 zerotd = timedelta(0)
992 self.assertRaises(ZeroDivisionError, truediv, t, zerotd)
993 self.assertRaises(ZeroDivisionError, floordiv, t, zerotd)
994
995 # self.assertRaises(TypeError, truediv, t, 2)
996 # note: floor division of a timedelta by an integer *is*
997 # currently permitted.
998
999 def test_remainder(self):
1000 t = timedelta(minutes=2, seconds=30)
1001 minute = timedelta(minutes=1)
1002 r = t % minute
1003 self.assertEqual(r, timedelta(seconds=30))
1004
1005 t = timedelta(minutes=-2, seconds=30)
1006 r = t % minute
1007 self.assertEqual(r, timedelta(seconds=30))
1008
1009 zerotd = timedelta(0)
1010 self.assertRaises(ZeroDivisionError, mod, t, zerotd)
1011
1012 self.assertRaises(TypeError, mod, t, 10)
1013
1014 def test_divmod(self):
1015 t = timedelta(minutes=2, seconds=30)
1016 minute = timedelta(minutes=1)
1017 q, r = divmod(t, minute)
1018 self.assertEqual(q, 2)
1019 self.assertEqual(r, timedelta(seconds=30))
1020
1021 t = timedelta(minutes=-2, seconds=30)
1022 q, r = divmod(t, minute)
1023 self.assertEqual(q, -2)
1024 self.assertEqual(r, timedelta(seconds=30))
1025
1026 zerotd = timedelta(0)
1027 self.assertRaises(ZeroDivisionError, divmod, t, zerotd)
1028
1029 self.assertRaises(TypeError, divmod, t, 10)
1030
1031 def test_issue31293(self):
1032 # The interpreter shouldn't crash in case a timedelta is divided or
1033 # multiplied by a float with a bad as_integer_ratio() method.
1034 def get_bad_float(bad_ratio):
1035 class BadFloat(float):
1036 def as_integer_ratio(self):
1037 return bad_ratio
1038 return BadFloat()
1039
1040 with self.assertRaises(TypeError):
1041 timedelta() / get_bad_float(1 << 1000)
1042 with self.assertRaises(TypeError):
1043 timedelta() * get_bad_float(1 << 1000)
1044
1045 for bad_ratio in [(), (42, ), (1, 2, 3)]:
1046 with self.assertRaises(ValueError):
1047 timedelta() / get_bad_float(bad_ratio)
1048 with self.assertRaises(ValueError):
1049 timedelta() * get_bad_float(bad_ratio)
1050
1051 def test_issue31752(self):
1052 # The interpreter shouldn't crash because divmod() returns negative
1053 # remainder.
1054 class BadInt(int):
1055 def __mul__(self, other):
1056 return Prod()
1057 def __rmul__(self, other):
1058 return Prod()
1059 def __floordiv__(self, other):
1060 return Prod()
1061 def __rfloordiv__(self, other):
1062 return Prod()
1063
1064 class Prod:
1065 def __add__(self, other):
1066 return Sum()
1067 def __radd__(self, other):
1068 return Sum()
1069
1070 class Sum(int):
1071 def __divmod__(self, other):
1072 return divmodresult
1073
1074 for divmodresult in [None, (), (0, 1, 2), (0, -1)]:
1075 with self.subTest(divmodresult=divmodresult):
1076 # The following examples should not crash.
1077 try:
1078 timedelta(microseconds=BadInt(1))
1079 except TypeError:
1080 pass
1081 try:
1082 timedelta(hours=BadInt(1))
1083 except TypeError:
1084 pass
1085 try:
1086 timedelta(weeks=BadInt(1))
1087 except (TypeError, ValueError):
1088 pass
1089 try:
1090 timedelta(1) * BadInt(1)
1091 except (TypeError, ValueError):
1092 pass
1093 try:
1094 BadInt(1) * timedelta(1)
1095 except TypeError:
1096 pass
1097 try:
1098 timedelta(1) // BadInt(1)
1099 except TypeError:
1100 pass
1101
1102
1103 #############################################################################
1104 # date tests
1105
1106 class TestDateOnly(unittest.TestCase):
1107 # Tests here won't pass if also run on datetime objects, so don't
1108 # subclass this to test datetimes too.
1109
1110 def test_delta_non_days_ignored(self):
1111 dt = date(2000, 1, 2)
1112 delta = timedelta(days=1, hours=2, minutes=3, seconds=4,
1113 microseconds=5)
1114 days = timedelta(delta.days)
1115 self.assertEqual(days, timedelta(1))
1116
1117 dt2 = dt + delta
1118 self.assertEqual(dt2, dt + days)
1119
1120 dt2 = delta + dt
1121 self.assertEqual(dt2, dt + days)
1122
1123 dt2 = dt - delta
1124 self.assertEqual(dt2, dt - days)
1125
1126 delta = -delta
1127 days = timedelta(delta.days)
1128 self.assertEqual(days, timedelta(-2))
1129
1130 dt2 = dt + delta
1131 self.assertEqual(dt2, dt + days)
1132
1133 dt2 = delta + dt
1134 self.assertEqual(dt2, dt + days)
1135
1136 dt2 = dt - delta
1137 self.assertEqual(dt2, dt - days)
1138
1139 def test_strptime(self):
1140 inputs = [
1141 # Basic valid cases
1142 (date(1998, 2, 3), '1998-02-03', '%Y-%m-%d'),
1143 (date(2004, 12, 2), '2004-12-02', '%Y-%m-%d'),
1144
1145 # Edge cases: Leap year
1146 (date(2020, 2, 29), '2020-02-29', '%Y-%m-%d'), # Valid leap year date
1147
1148 # bpo-34482: Handle surrogate pairs
1149 (date(2004, 12, 2), '2004-12\ud80002', '%Y-%m\ud800%d'),
1150 (date(2004, 12, 2), '2004\ud80012-02', '%Y\ud800%m-%d'),
1151
1152 # Month/day variations
1153 (date(2004, 2, 1), '2004-02', '%Y-%m'), # No day provided
1154 (date(2004, 2, 1), '02-2004', '%m-%Y'), # Month and year swapped
1155
1156 # Different day-month-year formats
1157 (date(2004, 12, 2), '02/12/2004', '%d/%m/%Y'), # Day/Month/Year
1158 (date(2004, 12, 2), '12/02/2004', '%m/%d/%Y'), # Month/Day/Year
1159
1160 # Different separators
1161 (date(2023, 9, 24), '24.09.2023', '%d.%m.%Y'), # Dots as separators
1162 (date(2023, 9, 24), '24-09-2023', '%d-%m-%Y'), # Dashes
1163 (date(2023, 9, 24), '2023/09/24', '%Y/%m/%d'), # Slashes
1164
1165 # Handling years with fewer digits
1166 (date(127, 2, 3), '0127-02-03', '%Y-%m-%d'),
1167 (date(99, 2, 3), '0099-02-03', '%Y-%m-%d'),
1168 (date(5, 2, 3), '0005-02-03', '%Y-%m-%d'),
1169
1170 # Variations on ISO 8601 format
1171 (date(2023, 9, 25), '2023-W39-1', '%G-W%V-%u'), # ISO week date (Week 39, Monday)
1172 (date(2023, 9, 25), '2023-268', '%Y-%j'), # Year and day of the year (Julian)
1173 ]
1174 for expected, string, format in inputs:
1175 with self.subTest(string=string, format=format):
1176 got = date.strptime(string, format)
1177 self.assertEqual(expected, got)
1178 self.assertIs(type(got), date)
1179
1180 def test_strptime_single_digit(self):
1181 # bpo-34903: Check that single digit dates are allowed.
1182 strptime = date.strptime
1183 with self.assertRaises(ValueError):
1184 # %y does require two digits.
1185 newdate = strptime('01/02/3', '%d/%m/%y')
1186
1187 d1 = date(2003, 2, 1)
1188 d2 = date(2003, 1, 2)
1189 d3 = date(2003, 1, 25)
1190 inputs = [
1191 ('%d', '1/02/03', '%d/%m/%y', d1),
1192 ('%m', '01/2/03', '%d/%m/%y', d1),
1193 ('%j', '2/03', '%j/%y', d2),
1194 ('%w', '6/04/03', '%w/%U/%y', d1),
1195 # %u requires a single digit.
1196 ('%W', '6/4/2003', '%u/%W/%Y', d1),
1197 ('%V', '6/4/2003', '%u/%V/%G', d3),
1198 ]
1199 for reason, string, format, target in inputs:
1200 reason = 'test single digit ' + reason
1201 with self.subTest(reason=reason,
1202 string=string,
1203 format=format,
1204 target=target):
1205 newdate = strptime(string, format)
1206 self.assertEqual(newdate, target, msg=reason)
1207
1208 @warnings_helper.ignore_warnings(category=DeprecationWarning)
1209 def test_strptime_leap_year(self):
1210 # GH-70647: warns if parsing a format with a day and no year.
1211 with self.assertRaises(ValueError):
1212 # The existing behavior that GH-70647 seeks to change.
1213 date.strptime('02-29', '%m-%d')
1214 with self._assertNotWarns(DeprecationWarning):
1215 date.strptime('20-03-14', '%y-%m-%d')
1216 date.strptime('02-29,2024', '%m-%d,%Y')
1217
1218 class SubclassDate(date):
1219 sub_var = 1
1220
1221 class TestDate(HarmlessMixedComparison, unittest.TestCase):
1222 # Tests here should pass for both dates and datetimes, except for a
1223 # few tests that TestDateTime overrides.
1224
1225 theclass = date
1226
1227 def test_basic_attributes(self):
1228 dt = self.theclass(2002, 3, 1)
1229 self.assertEqual(dt.year, 2002)
1230 self.assertEqual(dt.month, 3)
1231 self.assertEqual(dt.day, 1)
1232
1233 def test_roundtrip(self):
1234 for dt in (self.theclass(1, 2, 3),
1235 self.theclass.today()):
1236 # Verify dt -> string -> date identity.
1237 s = repr(dt)
1238 self.assertStartsWith(s, 'datetime.')
1239 s = s[9:]
1240 dt2 = eval(s)
1241 self.assertEqual(dt, dt2)
1242
1243 # Verify identity via reconstructing from pieces.
1244 dt2 = self.theclass(dt.year, dt.month, dt.day)
1245 self.assertEqual(dt, dt2)
1246
1247 def test_repr_subclass(self):
1248 """Subclasses should have bare names in the repr (gh-107773)."""
1249 td = SubclassDate(1, 2, 3)
1250 self.assertEqual(repr(td), "SubclassDate(1, 2, 3)")
1251 td = SubclassDate(2014, 1, 1)
1252 self.assertEqual(repr(td), "SubclassDate(2014, 1, 1)")
1253 td = SubclassDate(2010, 10, day=10)
1254 self.assertEqual(repr(td), "SubclassDate(2010, 10, 10)")
1255
1256 def test_ordinal_conversions(self):
1257 # Check some fixed values.
1258 for y, m, d, n in [(1, 1, 1, 1), # calendar origin
1259 (1, 12, 31, 365),
1260 (2, 1, 1, 366),
1261 # first example from "Calendrical Calculations"
1262 (1945, 11, 12, 710347)]:
1263 d = self.theclass(y, m, d)
1264 self.assertEqual(n, d.toordinal())
1265 fromord = self.theclass.fromordinal(n)
1266 self.assertEqual(d, fromord)
1267 if hasattr(fromord, "hour"):
1268 # if we're checking something fancier than a date, verify
1269 # the extra fields have been zeroed out
1270 self.assertEqual(fromord.hour, 0)
1271 self.assertEqual(fromord.minute, 0)
1272 self.assertEqual(fromord.second, 0)
1273 self.assertEqual(fromord.microsecond, 0)
1274
1275 # Check first and last days of year spottily across the whole
1276 # range of years supported.
1277 for year in range(MINYEAR, MAXYEAR+1, 7):
1278 # Verify (year, 1, 1) -> ordinal -> y, m, d is identity.
1279 d = self.theclass(year, 1, 1)
1280 n = d.toordinal()
1281 d2 = self.theclass.fromordinal(n)
1282 self.assertEqual(d, d2)
1283 # Verify that moving back a day gets to the end of year-1.
1284 if year > 1:
1285 d = self.theclass.fromordinal(n-1)
1286 d2 = self.theclass(year-1, 12, 31)
1287 self.assertEqual(d, d2)
1288 self.assertEqual(d2.toordinal(), n-1)
1289
1290 # Test every day in a leap-year and a non-leap year.
1291 dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
1292 for year, isleap in (2000, True), (2002, False):
1293 n = self.theclass(year, 1, 1).toordinal()
1294 for month, maxday in zip(range(1, 13), dim):
1295 if month == 2 and isleap:
1296 maxday += 1
1297 for day in range(1, maxday+1):
1298 d = self.theclass(year, month, day)
1299 self.assertEqual(d.toordinal(), n)
1300 self.assertEqual(d, self.theclass.fromordinal(n))
1301 n += 1
1302
1303 def test_extreme_ordinals(self):
1304 a = self.theclass.min
1305 a = self.theclass(a.year, a.month, a.day) # get rid of time parts
1306 aord = a.toordinal()
1307 b = a.fromordinal(aord)
1308 self.assertEqual(a, b)
1309
1310 self.assertRaises(ValueError, lambda: a.fromordinal(aord - 1))
1311
1312 b = a + timedelta(days=1)
1313 self.assertEqual(b.toordinal(), aord + 1)
1314 self.assertEqual(b, self.theclass.fromordinal(aord + 1))
1315
1316 a = self.theclass.max
1317 a = self.theclass(a.year, a.month, a.day) # get rid of time parts
1318 aord = a.toordinal()
1319 b = a.fromordinal(aord)
1320 self.assertEqual(a, b)
1321
1322 self.assertRaises(ValueError, lambda: a.fromordinal(aord + 1))
1323
1324 b = a - timedelta(days=1)
1325 self.assertEqual(b.toordinal(), aord - 1)
1326 self.assertEqual(b, self.theclass.fromordinal(aord - 1))
1327
1328 def test_bad_constructor_arguments(self):
1329 # bad years
1330 self.theclass(MINYEAR, 1, 1) # no exception
1331 self.theclass(MAXYEAR, 1, 1) # no exception
1332 self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1)
1333 self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1)
1334 # bad months
1335 self.theclass(2000, 1, 1) # no exception
1336 self.theclass(2000, 12, 1) # no exception
1337 self.assertRaises(ValueError, self.theclass, 2000, 0, 1)
1338 self.assertRaises(ValueError, self.theclass, 2000, 13, 1)
1339 # bad days
1340 self.theclass(2000, 2, 29) # no exception
1341 self.theclass(2004, 2, 29) # no exception
1342 self.theclass(2400, 2, 29) # no exception
1343 self.assertRaises(ValueError, self.theclass, 2000, 2, 30)
1344 self.assertRaises(ValueError, self.theclass, 2001, 2, 29)
1345 self.assertRaises(ValueError, self.theclass, 2100, 2, 29)
1346 self.assertRaises(ValueError, self.theclass, 1900, 2, 29)
1347 self.assertRaises(ValueError, self.theclass, 2000, 1, 0)
1348 self.assertRaises(ValueError, self.theclass, 2000, 1, 32)
1349
1350 def test_hash_equality(self):
1351 d = self.theclass(2000, 12, 31)
1352 # same thing
1353 e = self.theclass(2000, 12, 31)
1354 self.assertEqual(d, e)
1355 self.assertEqual(hash(d), hash(e))
1356
1357 dic = {d: 1}
1358 dic[e] = 2
1359 self.assertEqual(len(dic), 1)
1360 self.assertEqual(dic[d], 2)
1361 self.assertEqual(dic[e], 2)
1362
1363 d = self.theclass(2001, 1, 1)
1364 # same thing
1365 e = self.theclass(2001, 1, 1)
1366 self.assertEqual(d, e)
1367 self.assertEqual(hash(d), hash(e))
1368
1369 dic = {d: 1}
1370 dic[e] = 2
1371 self.assertEqual(len(dic), 1)
1372 self.assertEqual(dic[d], 2)
1373 self.assertEqual(dic[e], 2)
1374
1375 def test_computations(self):
1376 a = self.theclass(2002, 1, 31)
1377 b = self.theclass(1956, 1, 31)
1378 c = self.theclass(2001,2,1)
1379
1380 diff = a-b
1381 self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4)))
1382 self.assertEqual(diff.seconds, 0)
1383 self.assertEqual(diff.microseconds, 0)
1384
1385 day = timedelta(1)
1386 week = timedelta(7)
1387 a = self.theclass(2002, 3, 2)
1388 self.assertEqual(a + day, self.theclass(2002, 3, 3))
1389 self.assertEqual(day + a, self.theclass(2002, 3, 3))
1390 self.assertEqual(a - day, self.theclass(2002, 3, 1))
1391 self.assertEqual(-day + a, self.theclass(2002, 3, 1))
1392 self.assertEqual(a + week, self.theclass(2002, 3, 9))
1393 self.assertEqual(a - week, self.theclass(2002, 2, 23))
1394 self.assertEqual(a + 52*week, self.theclass(2003, 3, 1))
1395 self.assertEqual(a - 52*week, self.theclass(2001, 3, 3))
1396 self.assertEqual((a + week) - a, week)
1397 self.assertEqual((a + day) - a, day)
1398 self.assertEqual((a - week) - a, -week)
1399 self.assertEqual((a - day) - a, -day)
1400 self.assertEqual(a - (a + week), -week)
1401 self.assertEqual(a - (a + day), -day)
1402 self.assertEqual(a - (a - week), week)
1403 self.assertEqual(a - (a - day), day)
1404 self.assertEqual(c - (c - day), day)
1405
1406 # Add/sub ints or floats should be illegal
1407 for i in 1, 1.0:
1408 self.assertRaises(TypeError, lambda: a+i)
1409 self.assertRaises(TypeError, lambda: a-i)
1410 self.assertRaises(TypeError, lambda: i+a)
1411 self.assertRaises(TypeError, lambda: i-a)
1412
1413 # delta - date is senseless.
1414 self.assertRaises(TypeError, lambda: day - a)
1415 # mixing date and (delta or date) via * or // is senseless
1416 self.assertRaises(TypeError, lambda: day * a)
1417 self.assertRaises(TypeError, lambda: a * day)
1418 self.assertRaises(TypeError, lambda: day // a)
1419 self.assertRaises(TypeError, lambda: a // day)
1420 self.assertRaises(TypeError, lambda: a * a)
1421 self.assertRaises(TypeError, lambda: a // a)
1422 # date + date is senseless
1423 self.assertRaises(TypeError, lambda: a + a)
1424
1425 def test_overflow(self):
1426 tiny = self.theclass.resolution
1427
1428 for delta in [tiny, timedelta(1), timedelta(2)]:
1429 dt = self.theclass.min + delta
1430 dt -= delta # no problem
1431 self.assertRaises(OverflowError, dt.__sub__, delta)
1432 self.assertRaises(OverflowError, dt.__add__, -delta)
1433
1434 dt = self.theclass.max - delta
1435 dt += delta # no problem
1436 self.assertRaises(OverflowError, dt.__add__, delta)
1437 self.assertRaises(OverflowError, dt.__sub__, -delta)
1438
1439 def test_fromtimestamp(self):
1440 import time
1441
1442 # Try an arbitrary fixed value.
1443 year, month, day = 1999, 9, 19
1444 ts = time.mktime((year, month, day, 0, 0, 0, 0, 0, -1))
1445 d = self.theclass.fromtimestamp(ts)
1446 self.assertEqual(d.year, year)
1447 self.assertEqual(d.month, month)
1448 self.assertEqual(d.day, day)
1449
1450 def test_insane_fromtimestamp(self):
1451 # It's possible that some platform maps time_t to double,
1452 # and that this test will fail there. This test should
1453 # exempt such platforms (provided they return reasonable
1454 # results!).
1455 for insane in -1e200, 1e200:
1456 self.assertRaises(OverflowError, self.theclass.fromtimestamp,
1457 insane)
1458
1459 def test_fromtimestamp_with_none_arg(self):
1460 # See gh-120268 for more details
1461 with self.assertRaises(TypeError):
1462 self.theclass.fromtimestamp(None)
1463
1464 def test_today(self):
1465 import time
1466
1467 # We claim that today() is like fromtimestamp(time.time()), so
1468 # prove it.
1469 for dummy in range(3):
1470 today = self.theclass.today()
1471 ts = time.time()
1472 todayagain = self.theclass.fromtimestamp(ts)
1473 if today == todayagain:
1474 break
1475 # There are several legit reasons that could fail:
1476 # 1. It recently became midnight, between the today() and the
1477 # time() calls.
1478 # 2. The platform time() has such fine resolution that we'll
1479 # never get the same value twice.
1480 # 3. The platform time() has poor resolution, and we just
1481 # happened to call today() right before a resolution quantum
1482 # boundary.
1483 # 4. The system clock got fiddled between calls.
1484 # In any case, wait a little while and try again.
1485 time.sleep(0.1)
1486
1487 # It worked or it didn't. If it didn't, assume it's reason #2, and
1488 # let the test pass if they're within half a second of each other.
1489 if today != todayagain:
1490 self.assertAlmostEqual(todayagain, today,
1491 delta=timedelta(seconds=0.5))
1492
1493 def test_weekday(self):
1494 for i in range(7):
1495 # March 4, 2002 is a Monday
1496 self.assertEqual(self.theclass(2002, 3, 4+i).weekday(), i)
1497 self.assertEqual(self.theclass(2002, 3, 4+i).isoweekday(), i+1)
1498 # January 2, 1956 is a Monday
1499 self.assertEqual(self.theclass(1956, 1, 2+i).weekday(), i)
1500 self.assertEqual(self.theclass(1956, 1, 2+i).isoweekday(), i+1)
1501
1502 def test_isocalendar(self):
1503 # Check examples from
1504 # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
1505 week_mondays = [
1506 ((2003, 12, 22), (2003, 52, 1)),
1507 ((2003, 12, 29), (2004, 1, 1)),
1508 ((2004, 1, 5), (2004, 2, 1)),
1509 ((2009, 12, 21), (2009, 52, 1)),
1510 ((2009, 12, 28), (2009, 53, 1)),
1511 ((2010, 1, 4), (2010, 1, 1)),
1512 ]
1513
1514 test_cases = []
1515 for cal_date, iso_date in week_mondays:
1516 base_date = self.theclass(*cal_date)
1517 # Adds one test case for every day of the specified weeks
1518 for i in range(7):
1519 new_date = base_date + timedelta(i)
1520 new_iso = iso_date[0:2] + (iso_date[2] + i,)
1521 test_cases.append((new_date, new_iso))
1522
1523 for d, exp_iso in test_cases:
1524 with self.subTest(d=d, comparison="tuple"):
1525 self.assertEqual(d.isocalendar(), exp_iso)
1526
1527 # Check that the tuple contents are accessible by field name
1528 with self.subTest(d=d, comparison="fields"):
1529 t = d.isocalendar()
1530 self.assertEqual((t.year, t.week, t.weekday), exp_iso)
1531
1532 def test_isocalendar_pickling(self):
1533 """Test that the result of datetime.isocalendar() can be pickled.
1534
1535 The result of a round trip should be a plain tuple.
1536 """
1537 d = self.theclass(2019, 1, 1)
1538 p = pickle.dumps(d.isocalendar())
1539 res = pickle.loads(p)
1540 self.assertEqual(type(res), tuple)
1541 self.assertEqual(res, (2019, 1, 2))
1542
1543 def test_iso_long_years(self):
1544 # Calculate long ISO years and compare to table from
1545 # http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm
1546 ISO_LONG_YEARS_TABLE = """
1547 4 32 60 88
1548 9 37 65 93
1549 15 43 71 99
1550 20 48 76
1551 26 54 82
1552
1553 105 133 161 189
1554 111 139 167 195
1555 116 144 172
1556 122 150 178
1557 128 156 184
1558
1559 201 229 257 285
1560 207 235 263 291
1561 212 240 268 296
1562 218 246 274
1563 224 252 280
1564
1565 303 331 359 387
1566 308 336 364 392
1567 314 342 370 398
1568 320 348 376
1569 325 353 381
1570 """
1571 iso_long_years = sorted(map(int, ISO_LONG_YEARS_TABLE.split()))
1572 L = []
1573 for i in range(400):
1574 d = self.theclass(2000+i, 12, 31)
1575 d1 = self.theclass(1600+i, 12, 31)
1576 self.assertEqual(d.isocalendar()[1:], d1.isocalendar()[1:])
1577 if d.isocalendar()[1] == 53:
1578 L.append(i)
1579 self.assertEqual(L, iso_long_years)
1580
1581 def test_isoformat(self):
1582 t = self.theclass(2, 3, 2)
1583 self.assertEqual(t.isoformat(), "0002-03-02")
1584
1585 def test_ctime(self):
1586 t = self.theclass(2002, 3, 2)
1587 self.assertEqual(t.ctime(), "Sat Mar 2 00:00:00 2002")
1588
1589 def test_strftime(self):
1590 t = self.theclass(2005, 3, 2)
1591 self.assertEqual(t.strftime("m:%m d:%d y:%y"), "m:03 d:02 y:05")
1592 self.assertEqual(t.strftime(""), "") # SF bug #761337
1593 self.assertEqual(t.strftime('x'*1000), 'x'*1000) # SF bug #1556784
1594
1595 self.assertRaises(TypeError, t.strftime) # needs an arg
1596 self.assertRaises(TypeError, t.strftime, "one", "two") # too many args
1597 self.assertRaises(TypeError, t.strftime, 42) # arg wrong type
1598
1599 # test that unicode input is allowed (issue 2782)
1600 self.assertEqual(t.strftime("%m"), "03")
1601
1602 # A naive object replaces %z, %:z and %Z w/ empty strings.
1603 self.assertEqual(t.strftime("'%z' '%:z' '%Z'"), "'' '' ''")
1604
1605 #make sure that invalid format specifiers are handled correctly
1606 #self.assertRaises(ValueError, t.strftime, "%e")
1607 #self.assertRaises(ValueError, t.strftime, "%")
1608 #self.assertRaises(ValueError, t.strftime, "%#")
1609
1610 #oh well, some systems just ignore those invalid ones.
1611 #at least, exercise them to make sure that no crashes
1612 #are generated
1613 for f in ["%e", "%", "%#"]:
1614 try:
1615 t.strftime(f)
1616 except ValueError:
1617 pass
1618
1619 # bpo-34482: Check that surrogates don't cause a crash.
1620 try:
1621 t.strftime('%y\ud800%m')
1622 except UnicodeEncodeError:
1623 pass
1624
1625 #check that this standard extension works
1626 t.strftime("%f")
1627
1628 # bpo-41260: The parameter was named "fmt" in the pure python impl.
1629 t.strftime(format="%f")
1630
1631 def test_strftime_trailing_percent(self):
1632 # bpo-35066: Make sure trailing '%' doesn't cause datetime's strftime to
1633 # complain. Different libcs have different handling of trailing
1634 # percents, so we simply check datetime's strftime acts the same as
1635 # time.strftime.
1636 t = self.theclass(2005, 3, 2)
1637 try:
1638 _time.strftime('%')
1639 except ValueError:
1640 self.skipTest('time module does not support trailing %')
1641 self.assertEqual(t.strftime('%'), _time.strftime('%', t.timetuple()))
1642 self.assertEqual(
1643 t.strftime("m:%m d:%d y:%y %"),
1644 _time.strftime("m:03 d:02 y:05 %", t.timetuple()),
1645 )
1646
1647 def test_format(self):
1648 dt = self.theclass(2007, 9, 10)
1649 self.assertEqual(dt.__format__(''), str(dt))
1650
1651 with self.assertRaisesRegex(TypeError, 'must be str, not int'):
1652 dt.__format__(123)
1653
1654 # check that a derived class's __str__() gets called
1655 class A(self.theclass):
1656 def __str__(self):
1657 return 'A'
1658 a = A(2007, 9, 10)
1659 self.assertEqual(a.__format__(''), 'A')
1660
1661 # check that a derived class's strftime gets called
1662 class B(self.theclass):
1663 def strftime(self, format_spec):
1664 return 'B'
1665 b = B(2007, 9, 10)
1666 self.assertEqual(b.__format__(''), str(dt))
1667
1668 for fmt in ["m:%m d:%d y:%y",
1669 "m:%m d:%d y:%y H:%H M:%M S:%S",
1670 "%z %:z %Z",
1671 ]:
1672 self.assertEqual(dt.__format__(fmt), dt.strftime(fmt))
1673 self.assertEqual(a.__format__(fmt), dt.strftime(fmt))
1674 self.assertEqual(b.__format__(fmt), 'B')
1675
1676 def test_resolution_info(self):
1677 # XXX: Should min and max respect subclassing?
1678 if issubclass(self.theclass, datetime):
1679 expected_class = datetime
1680 else:
1681 expected_class = date
1682 self.assertIsInstance(self.theclass.min, expected_class)
1683 self.assertIsInstance(self.theclass.max, expected_class)
1684 self.assertIsInstance(self.theclass.resolution, timedelta)
1685 self.assertTrue(self.theclass.max > self.theclass.min)
1686
1687 def test_extreme_timedelta(self):
1688 big = self.theclass.max - self.theclass.min
1689 # 3652058 days, 23 hours, 59 minutes, 59 seconds, 999999 microseconds
1690 n = (big.days*24*3600 + big.seconds)*1000000 + big.microseconds
1691 # n == 315537897599999999 ~= 2**58.13
1692 justasbig = timedelta(0, 0, n)
1693 self.assertEqual(big, justasbig)
1694 self.assertEqual(self.theclass.min + big, self.theclass.max)
1695 self.assertEqual(self.theclass.max - big, self.theclass.min)
1696
1697 def test_timetuple(self):
1698 for i in range(7):
1699 # January 2, 1956 is a Monday (0)
1700 d = self.theclass(1956, 1, 2+i)
1701 t = d.timetuple()
1702 self.assertEqual(t, (1956, 1, 2+i, 0, 0, 0, i, 2+i, -1))
1703 # February 1, 1956 is a Wednesday (2)
1704 d = self.theclass(1956, 2, 1+i)
1705 t = d.timetuple()
1706 self.assertEqual(t, (1956, 2, 1+i, 0, 0, 0, (2+i)%7, 32+i, -1))
1707 # March 1, 1956 is a Thursday (3), and is the 31+29+1 = 61st day
1708 # of the year.
1709 d = self.theclass(1956, 3, 1+i)
1710 t = d.timetuple()
1711 self.assertEqual(t, (1956, 3, 1+i, 0, 0, 0, (3+i)%7, 61+i, -1))
1712 self.assertEqual(t.tm_year, 1956)
1713 self.assertEqual(t.tm_mon, 3)
1714 self.assertEqual(t.tm_mday, 1+i)
1715 self.assertEqual(t.tm_hour, 0)
1716 self.assertEqual(t.tm_min, 0)
1717 self.assertEqual(t.tm_sec, 0)
1718 self.assertEqual(t.tm_wday, (3+i)%7)
1719 self.assertEqual(t.tm_yday, 61+i)
1720 self.assertEqual(t.tm_isdst, -1)
1721
1722 def test_pickling(self):
1723 args = 6, 7, 23
1724 orig = self.theclass(*args)
1725 for pickler, unpickler, proto in pickle_choices:
1726 green = pickler.dumps(orig, proto)
1727 derived = unpickler.loads(green)
1728 self.assertEqual(orig, derived)
1729 self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2))
1730
1731 def test_compat_unpickle(self):
1732 tests = [
1733 b"cdatetime\ndate\n(S'\\x07\\xdf\\x0b\\x1b'\ntR.",
1734 b'cdatetime\ndate\n(U\x04\x07\xdf\x0b\x1btR.',
1735 b'\x80\x02cdatetime\ndate\nU\x04\x07\xdf\x0b\x1b\x85R.',
1736 ]
1737 args = 2015, 11, 27
1738 expected = self.theclass(*args)
1739 for data in tests:
1740 for loads in pickle_loads:
1741 derived = loads(data, encoding='latin1')
1742 self.assertEqual(derived, expected)
1743
1744 def test_compare(self):
1745 t1 = self.theclass(2, 3, 4)
1746 t2 = self.theclass(2, 3, 4)
1747 self.assertEqual(t1, t2)
1748 self.assertTrue(t1 <= t2)
1749 self.assertTrue(t1 >= t2)
1750 self.assertFalse(t1 != t2)
1751 self.assertFalse(t1 < t2)
1752 self.assertFalse(t1 > t2)
1753
1754 for args in (3, 3, 3), (2, 4, 4), (2, 3, 5):
1755 t2 = self.theclass(*args) # this is larger than t1
1756 self.assertTrue(t1 < t2)
1757 self.assertTrue(t2 > t1)
1758 self.assertTrue(t1 <= t2)
1759 self.assertTrue(t2 >= t1)
1760 self.assertTrue(t1 != t2)
1761 self.assertTrue(t2 != t1)
1762 self.assertFalse(t1 == t2)
1763 self.assertFalse(t2 == t1)
1764 self.assertFalse(t1 > t2)
1765 self.assertFalse(t2 < t1)
1766 self.assertFalse(t1 >= t2)
1767 self.assertFalse(t2 <= t1)
1768
1769 for badarg in OTHERSTUFF:
1770 self.assertEqual(t1 == badarg, False)
1771 self.assertEqual(t1 != badarg, True)
1772 self.assertEqual(badarg == t1, False)
1773 self.assertEqual(badarg != t1, True)
1774
1775 self.assertRaises(TypeError, lambda: t1 < badarg)
1776 self.assertRaises(TypeError, lambda: t1 > badarg)
1777 self.assertRaises(TypeError, lambda: t1 >= badarg)
1778 self.assertRaises(TypeError, lambda: badarg <= t1)
1779 self.assertRaises(TypeError, lambda: badarg < t1)
1780 self.assertRaises(TypeError, lambda: badarg > t1)
1781 self.assertRaises(TypeError, lambda: badarg >= t1)
1782
1783 def test_mixed_compare(self):
1784 our = self.theclass(2000, 4, 5)
1785
1786 # Our class can be compared for equality to other classes
1787 self.assertEqual(our == 1, False)
1788 self.assertEqual(1 == our, False)
1789 self.assertEqual(our != 1, True)
1790 self.assertEqual(1 != our, True)
1791
1792 # But the ordering is undefined
1793 self.assertRaises(TypeError, lambda: our < 1)
1794 self.assertRaises(TypeError, lambda: 1 < our)
1795
1796 # Repeat those tests with a different class
1797
1798 class SomeClass:
1799 pass
1800
1801 their = SomeClass()
1802 self.assertEqual(our == their, False)
1803 self.assertEqual(their == our, False)
1804 self.assertEqual(our != their, True)
1805 self.assertEqual(their != our, True)
1806 self.assertRaises(TypeError, lambda: our < their)
1807 self.assertRaises(TypeError, lambda: their < our)
1808
1809 def test_bool(self):
1810 # All dates are considered true.
1811 self.assertTrue(self.theclass.min)
1812 self.assertTrue(self.theclass.max)
1813
1814 def check_strftime_y2k(self, specifier):
1815 # Test that years less than 1000 are 0-padded; note that the beginning
1816 # of an ISO 8601 year may fall in an ISO week of the year before, and
1817 # therefore needs an offset of -1 when formatting with '%G'.
1818 dataset = (
1819 (1, 0),
1820 (49, -1),
1821 (70, 0),
1822 (99, 0),
1823 (100, -1),
1824 (999, 0),
1825 (1000, 0),
1826 (1970, 0),
1827 )
1828 for year, g_offset in dataset:
1829 with self.subTest(year=year, specifier=specifier):
1830 d = self.theclass(year, 1, 1)
1831 if specifier == 'G':
1832 year += g_offset
1833 if specifier == 'C':
1834 expected = f"{year // 100:02d}"
1835 else:
1836 expected = f"{year:04d}"
1837 if specifier == 'F':
1838 expected += f"-01-01"
1839 self.assertEqual(d.strftime(f"%{specifier}"), expected)
1840
1841 def test_strftime_y2k(self):
1842 self.check_strftime_y2k('Y')
1843 self.check_strftime_y2k('G')
1844
1845 def test_strftime_y2k_c99(self):
1846 # CPython requires C11; specifiers new in C99 must work.
1847 # (Other implementations may want to disable this test.)
1848 self.check_strftime_y2k('F')
1849 self.check_strftime_y2k('C')
1850
1851 def test_replace(self):
1852 cls = self.theclass
1853 args = [1, 2, 3]
1854 base = cls(*args)
1855 self.assertEqual(base.replace(), base)
1856 self.assertEqual(copy.replace(base), base)
1857
1858 changes = (("year", 2),
1859 ("month", 3),
1860 ("day", 4))
1861 for i, (name, newval) in enumerate(changes):
1862 newargs = args[:]
1863 newargs[i] = newval
1864 expected = cls(*newargs)
1865 self.assertEqual(base.replace(**{name: newval}), expected)
1866 self.assertEqual(copy.replace(base, **{name: newval}), expected)
1867
1868 # Out of bounds.
1869 base = cls(2000, 2, 29)
1870 self.assertRaises(ValueError, base.replace, year=2001)
1871 self.assertRaises(ValueError, copy.replace, base, year=2001)
1872
1873 def test_subclass_replace(self):
1874 class DateSubclass(self.theclass):
1875 def __new__(cls, *args, **kwargs):
1876 result = self.theclass.__new__(cls, *args, **kwargs)
1877 result.extra = 7
1878 return result
1879
1880 dt = DateSubclass(2012, 1, 1)
1881
1882 test_cases = [
1883 ('self.replace', dt.replace(year=2013)),
1884 ('copy.replace', copy.replace(dt, year=2013)),
1885 ]
1886
1887 for name, res in test_cases:
1888 with self.subTest(name):
1889 self.assertIs(type(res), DateSubclass)
1890 self.assertEqual(res.year, 2013)
1891 self.assertEqual(res.month, 1)
1892 self.assertEqual(res.extra, 7)
1893
1894 def test_subclass_date(self):
1895
1896 class C(self.theclass):
1897 theAnswer = 42
1898
1899 def __new__(cls, *args, **kws):
1900 temp = kws.copy()
1901 extra = temp.pop('extra')
1902 result = self.theclass.__new__(cls, *args, **temp)
1903 result.extra = extra
1904 return result
1905
1906 def newmeth(self, start):
1907 return start + self.year + self.month
1908
1909 args = 2003, 4, 14
1910
1911 dt1 = self.theclass(*args)
1912 dt2 = C(*args, **{'extra': 7})
1913
1914 self.assertEqual(dt2.__class__, C)
1915 self.assertEqual(dt2.theAnswer, 42)
1916 self.assertEqual(dt2.extra, 7)
1917 self.assertEqual(dt1.toordinal(), dt2.toordinal())
1918 self.assertEqual(dt2.newmeth(-7), dt1.year + dt1.month - 7)
1919
1920 def test_subclass_alternate_constructors(self):
1921 # Test that alternate constructors call the constructor
1922 class DateSubclass(self.theclass):
1923 def __new__(cls, *args, **kwargs):
1924 result = self.theclass.__new__(cls, *args, **kwargs)
1925 result.extra = 7
1926
1927 return result
1928
1929 args = (2003, 4, 14)
1930 d_ord = 731319 # Equivalent ordinal date
1931 d_isoformat = '2003-04-14' # Equivalent isoformat()
1932
1933 base_d = DateSubclass(*args)
1934 self.assertIsInstance(base_d, DateSubclass)
1935 self.assertEqual(base_d.extra, 7)
1936
1937 # Timestamp depends on time zone, so we'll calculate the equivalent here
1938 ts = datetime.combine(base_d, time(0)).timestamp()
1939
1940 test_cases = [
1941 ('fromordinal', (d_ord,)),
1942 ('fromtimestamp', (ts,)),
1943 ('fromisoformat', (d_isoformat,)),
1944 ]
1945
1946 for constr_name, constr_args in test_cases:
1947 for base_obj in (DateSubclass, base_d):
1948 # Test both the classmethod and method
1949 with self.subTest(base_obj_type=type(base_obj),
1950 constr_name=constr_name):
1951 constr = getattr(base_obj, constr_name)
1952
1953 dt = constr(*constr_args)
1954
1955 # Test that it creates the right subclass
1956 self.assertIsInstance(dt, DateSubclass)
1957
1958 # Test that it's equal to the base object
1959 self.assertEqual(dt, base_d)
1960
1961 # Test that it called the constructor
1962 self.assertEqual(dt.extra, 7)
1963
1964 def test_pickling_subclass_date(self):
1965
1966 args = 6, 7, 23
1967 orig = SubclassDate(*args)
1968 for pickler, unpickler, proto in pickle_choices:
1969 green = pickler.dumps(orig, proto)
1970 derived = unpickler.loads(green)
1971 self.assertEqual(orig, derived)
1972 self.assertTrue(isinstance(derived, SubclassDate))
1973
1974 def test_backdoor_resistance(self):
1975 # For fast unpickling, the constructor accepts a pickle byte string.
1976 # This is a low-overhead backdoor. A user can (by intent or
1977 # mistake) pass a string directly, which (if it's the right length)
1978 # will get treated like a pickle, and bypass the normal sanity
1979 # checks in the constructor. This can create insane objects.
1980 # The constructor doesn't want to burn the time to validate all
1981 # fields, but does check the month field. This stops, e.g.,
1982 # datetime.datetime('1995-03-25') from yielding an insane object.
1983 base = b'1995-03-25'
1984 if not issubclass(self.theclass, datetime):
1985 base = base[:4]
1986 for month_byte in b'9', b'\0', b'\r', b'\xff':
1987 self.assertRaises(TypeError, self.theclass,
1988 base[:2] + month_byte + base[3:])
1989 if issubclass(self.theclass, datetime):
1990 # Good bytes, but bad tzinfo:
1991 with self.assertRaisesRegex(TypeError, '^bad tzinfo state arg$'):
1992 self.theclass(bytes([1] * len(base)), 'EST')
1993
1994 for ord_byte in range(1, 13):
1995 # This shouldn't blow up because of the month byte alone. If
1996 # the implementation changes to do more-careful checking, it may
1997 # blow up because other fields are insane.
1998 self.theclass(base[:2] + bytes([ord_byte]) + base[3:])
1999
2000 def test_valuerror_messages(self):
2001 pattern = re.compile(
2002 r"(year|month|day) must be in \d+\.\.\d+, not \d+"
2003 )
2004 test_cases = [
2005 (2009, 13, 1), # Month out of range
2006 (2009, 0, 1), # Month out of range
2007 (10000, 12, 31), # Year out of range
2008 (0, 12, 31), # Year out of range
2009 ]
2010 for case in test_cases:
2011 with self.subTest(case):
2012 with self.assertRaisesRegex(ValueError, pattern):
2013 self.theclass(*case)
2014
2015 # days out of range have their own error message, see issue 70647
2016 with self.assertRaises(ValueError) as msg:
2017 self.theclass(2009, 1, 32)
2018 self.assertIn(f"day 32 must be in range 1..31 for month 1 in year 2009", str(msg.exception))
2019
2020 def test_fromisoformat(self):
2021 # Test that isoformat() is reversible
2022 base_dates = [
2023 (1, 1, 1),
2024 (1000, 2, 14),
2025 (1900, 1, 1),
2026 (2000, 2, 29),
2027 (2004, 11, 12),
2028 (2004, 4, 3),
2029 (2017, 5, 30)
2030 ]
2031
2032 for dt_tuple in base_dates:
2033 dt = self.theclass(*dt_tuple)
2034 dt_str = dt.isoformat()
2035 with self.subTest(dt_str=dt_str):
2036 dt_rt = self.theclass.fromisoformat(dt.isoformat())
2037
2038 self.assertEqual(dt, dt_rt)
2039
2040 def test_fromisoformat_date_examples(self):
2041 examples = [
2042 ('00010101', self.theclass(1, 1, 1)),
2043 ('20000101', self.theclass(2000, 1, 1)),
2044 ('20250102', self.theclass(2025, 1, 2)),
2045 ('99991231', self.theclass(9999, 12, 31)),
2046 ('0001-01-01', self.theclass(1, 1, 1)),
2047 ('2000-01-01', self.theclass(2000, 1, 1)),
2048 ('2025-01-02', self.theclass(2025, 1, 2)),
2049 ('9999-12-31', self.theclass(9999, 12, 31)),
2050 ('2025W01', self.theclass(2024, 12, 30)),
2051 ('2025-W01', self.theclass(2024, 12, 30)),
2052 ('2025W014', self.theclass(2025, 1, 2)),
2053 ('2025-W01-4', self.theclass(2025, 1, 2)),
2054 ('2026W01', self.theclass(2025, 12, 29)),
2055 ('2026-W01', self.theclass(2025, 12, 29)),
2056 ('2026W013', self.theclass(2025, 12, 31)),
2057 ('2026-W01-3', self.theclass(2025, 12, 31)),
2058 ('2022W52', self.theclass(2022, 12, 26)),
2059 ('2022-W52', self.theclass(2022, 12, 26)),
2060 ('2022W527', self.theclass(2023, 1, 1)),
2061 ('2022-W52-7', self.theclass(2023, 1, 1)),
2062 ('2015W534', self.theclass(2015, 12, 31)), # Has week 53
2063 ('2015-W53-4', self.theclass(2015, 12, 31)), # Has week 53
2064 ('2015-W53-5', self.theclass(2016, 1, 1)),
2065 ('2020W531', self.theclass(2020, 12, 28)), # Leap year
2066 ('2020-W53-1', self.theclass(2020, 12, 28)), # Leap year
2067 ('2020-W53-6', self.theclass(2021, 1, 2)),
2068 ]
2069
2070 for input_str, expected in examples:
2071 with self.subTest(input_str=input_str):
2072 actual = self.theclass.fromisoformat(input_str)
2073 self.assertEqual(actual, expected)
2074
2075 def test_fromisoformat_subclass(self):
2076 class DateSubclass(self.theclass):
2077 pass
2078
2079 dt = DateSubclass(2014, 12, 14)
2080
2081 dt_rt = DateSubclass.fromisoformat(dt.isoformat())
2082
2083 self.assertIsInstance(dt_rt, DateSubclass)
2084
2085 def test_fromisoformat_fails(self):
2086 # Test that fromisoformat() fails on invalid values
2087 bad_strs = [
2088 '', # Empty string
2089 '\ud800', # bpo-34454: Surrogate code point
2090 '009-03-04', # Not 10 characters
2091 '123456789', # Not a date
2092 '200a-12-04', # Invalid character in year
2093 '2009-1a-04', # Invalid character in month
2094 '2009-12-0a', # Invalid character in day
2095 '2009-01-32', # Invalid day
2096 '2009-02-29', # Invalid leap day
2097 '2019-W53-1', # No week 53 in 2019
2098 '2020-W54-1', # No week 54
2099 '0000-W25-1', # Invalid year
2100 '10000-W25-1', # Invalid year
2101 '2020-W25-0', # Invalid day-of-week
2102 '2020-W25-8', # Invalid day-of-week
2103 '٢025-03-09' # Unicode characters
2104 '2009\ud80002\ud80028', # Separators are surrogate codepoints
2105 ]
2106
2107 for bad_str in bad_strs:
2108 with self.assertRaises(ValueError):
2109 self.theclass.fromisoformat(bad_str)
2110
2111 def test_fromisoformat_fails_typeerror(self):
2112 # Test that fromisoformat fails when passed the wrong type
2113 bad_types = [b'2009-03-01', None, io.StringIO('2009-03-01')]
2114 for bad_type in bad_types:
2115 with self.assertRaises(TypeError):
2116 self.theclass.fromisoformat(bad_type)
2117
2118 def test_fromisocalendar(self):
2119 # For each test case, assert that fromisocalendar is the
2120 # inverse of the isocalendar function
2121 dates = [
2122 (2016, 4, 3),
2123 (2005, 1, 2), # (2004, 53, 7)
2124 (2008, 12, 30), # (2009, 1, 2)
2125 (2010, 1, 2), # (2009, 53, 6)
2126 (2009, 12, 31), # (2009, 53, 4)
2127 (1900, 1, 1), # Unusual non-leap year (year % 100 == 0)
2128 (1900, 12, 31),
2129 (2000, 1, 1), # Unusual leap year (year % 400 == 0)
2130 (2000, 12, 31),
2131 (2004, 1, 1), # Leap year
2132 (2004, 12, 31),
2133 (1, 1, 1),
2134 (9999, 12, 31),
2135 (MINYEAR, 1, 1),
2136 (MAXYEAR, 12, 31),
2137 ]
2138
2139 for datecomps in dates:
2140 with self.subTest(datecomps=datecomps):
2141 dobj = self.theclass(*datecomps)
2142 isocal = dobj.isocalendar()
2143
2144 d_roundtrip = self.theclass.fromisocalendar(*isocal)
2145
2146 self.assertEqual(dobj, d_roundtrip)
2147
2148 def test_fromisocalendar_value_errors(self):
2149 isocals = [
2150 (2019, 0, 1),
2151 (2019, -1, 1),
2152 (2019, 54, 1),
2153 (2019, 1, 0),
2154 (2019, 1, -1),
2155 (2019, 1, 8),
2156 (2019, 53, 1),
2157 (10000, 1, 1),
2158 (0, 1, 1),
2159 (9999999, 1, 1),
2160 (2<<32, 1, 1),
2161 (2019, 2<<32, 1),
2162 (2019, 1, 2<<32),
2163 ]
2164
2165 for isocal in isocals:
2166 with self.subTest(isocal=isocal):
2167 with self.assertRaises(ValueError):
2168 self.theclass.fromisocalendar(*isocal)
2169
2170 def test_fromisocalendar_type_errors(self):
2171 err_txformers = [
2172 str,
2173 float,
2174 lambda x: None,
2175 ]
2176
2177 # Take a valid base tuple and transform it to contain one argument
2178 # with the wrong type. Repeat this for each argument, e.g.
2179 # [("2019", 1, 1), (2019, "1", 1), (2019, 1, "1"), ...]
2180 isocals = []
2181 base = (2019, 1, 1)
2182 for i in range(3):
2183 for txformer in err_txformers:
2184 err_val = list(base)
2185 err_val[i] = txformer(err_val[i])
2186 isocals.append(tuple(err_val))
2187
2188 for isocal in isocals:
2189 with self.subTest(isocal=isocal):
2190 with self.assertRaises(TypeError):
2191 self.theclass.fromisocalendar(*isocal)
2192
2193
2194 #############################################################################
2195 # datetime tests
2196
2197 class SubclassDatetime(datetime):
2198 sub_var = 1
2199
2200 class TestDateTime(TestDate):
2201
2202 theclass = datetime
2203
2204 def test_basic_attributes(self):
2205 dt = self.theclass(2002, 3, 1, 12, 0)
2206 self.assertEqual(dt.year, 2002)
2207 self.assertEqual(dt.month, 3)
2208 self.assertEqual(dt.day, 1)
2209 self.assertEqual(dt.hour, 12)
2210 self.assertEqual(dt.minute, 0)
2211 self.assertEqual(dt.second, 0)
2212 self.assertEqual(dt.microsecond, 0)
2213
2214 def test_basic_attributes_nonzero(self):
2215 # Make sure all attributes are non-zero so bugs in
2216 # bit-shifting access show up.
2217 dt = self.theclass(2002, 3, 1, 12, 59, 59, 8000)
2218 self.assertEqual(dt.year, 2002)
2219 self.assertEqual(dt.month, 3)
2220 self.assertEqual(dt.day, 1)
2221 self.assertEqual(dt.hour, 12)
2222 self.assertEqual(dt.minute, 59)
2223 self.assertEqual(dt.second, 59)
2224 self.assertEqual(dt.microsecond, 8000)
2225
2226 def test_roundtrip(self):
2227 for dt in (self.theclass(1, 2, 3, 4, 5, 6, 7),
2228 self.theclass.now()):
2229 # Verify dt -> string -> datetime identity.
2230 s = repr(dt)
2231 self.assertStartsWith(s, 'datetime.')
2232 s = s[9:]
2233 dt2 = eval(s)
2234 self.assertEqual(dt, dt2)
2235
2236 # Verify identity via reconstructing from pieces.
2237 dt2 = self.theclass(dt.year, dt.month, dt.day,
2238 dt.hour, dt.minute, dt.second,
2239 dt.microsecond)
2240 self.assertEqual(dt, dt2)
2241
2242 def test_isoformat(self):
2243 t = self.theclass(1, 2, 3, 4, 5, 1, 123)
2244 self.assertEqual(t.isoformat(), "0001-02-03T04:05:01.000123")
2245 self.assertEqual(t.isoformat('T'), "0001-02-03T04:05:01.000123")
2246 self.assertEqual(t.isoformat(' '), "0001-02-03 04:05:01.000123")
2247 self.assertEqual(t.isoformat('\x00'), "0001-02-03\x0004:05:01.000123")
2248 # bpo-34482: Check that surrogates are handled properly.
2249 self.assertEqual(t.isoformat('\ud800'),
2250 "0001-02-03\ud80004:05:01.000123")
2251 self.assertEqual(t.isoformat(timespec='hours'), "0001-02-03T04")
2252 self.assertEqual(t.isoformat(timespec='minutes'), "0001-02-03T04:05")
2253 self.assertEqual(t.isoformat(timespec='seconds'), "0001-02-03T04:05:01")
2254 self.assertEqual(t.isoformat(timespec='milliseconds'), "0001-02-03T04:05:01.000")
2255 self.assertEqual(t.isoformat(timespec='microseconds'), "0001-02-03T04:05:01.000123")
2256 self.assertEqual(t.isoformat(timespec='auto'), "0001-02-03T04:05:01.000123")
2257 self.assertEqual(t.isoformat(sep=' ', timespec='minutes'), "0001-02-03 04:05")
2258 self.assertRaises(ValueError, t.isoformat, timespec='foo')
2259 # bpo-34482: Check that surrogates are handled properly.
2260 self.assertRaises(ValueError, t.isoformat, timespec='\ud800')
2261 # str is ISO format with the separator forced to a blank.
2262 self.assertEqual(str(t), "0001-02-03 04:05:01.000123")
2263
2264 t = self.theclass(1, 2, 3, 4, 5, 1, 999500, tzinfo=timezone.utc)
2265 self.assertEqual(t.isoformat(timespec='milliseconds'), "0001-02-03T04:05:01.999+00:00")
2266
2267 t = self.theclass(1, 2, 3, 4, 5, 1, 999500)
2268 self.assertEqual(t.isoformat(timespec='milliseconds'), "0001-02-03T04:05:01.999")
2269
2270 t = self.theclass(1, 2, 3, 4, 5, 1)
2271 self.assertEqual(t.isoformat(timespec='auto'), "0001-02-03T04:05:01")
2272 self.assertEqual(t.isoformat(timespec='milliseconds'), "0001-02-03T04:05:01.000")
2273 self.assertEqual(t.isoformat(timespec='microseconds'), "0001-02-03T04:05:01.000000")
2274
2275 t = self.theclass(2, 3, 2)
2276 self.assertEqual(t.isoformat(), "0002-03-02T00:00:00")
2277 self.assertEqual(t.isoformat('T'), "0002-03-02T00:00:00")
2278 self.assertEqual(t.isoformat(' '), "0002-03-02 00:00:00")
2279 # str is ISO format with the separator forced to a blank.
2280 self.assertEqual(str(t), "0002-03-02 00:00:00")
2281 # ISO format with timezone
2282 tz = FixedOffset(timedelta(seconds=16), 'XXX')
2283 t = self.theclass(2, 3, 2, tzinfo=tz)
2284 self.assertEqual(t.isoformat(), "0002-03-02T00:00:00+00:00:16")
2285
2286 def test_isoformat_timezone(self):
2287 tzoffsets = [
2288 ('05:00', timedelta(hours=5)),
2289 ('02:00', timedelta(hours=2)),
2290 ('06:27', timedelta(hours=6, minutes=27)),
2291 ('12:32:30', timedelta(hours=12, minutes=32, seconds=30)),
2292 ('02:04:09.123456', timedelta(hours=2, minutes=4, seconds=9, microseconds=123456))
2293 ]
2294
2295 tzinfos = [
2296 ('', None),
2297 ('+00:00', timezone.utc),
2298 ('+00:00', timezone(timedelta(0))),
2299 ]
2300
2301 tzinfos += [
2302 (prefix + expected, timezone(sign * td))
2303 for expected, td in tzoffsets
2304 for prefix, sign in [('-', -1), ('+', 1)]
2305 ]
2306
2307 dt_base = self.theclass(2016, 4, 1, 12, 37, 9)
2308 exp_base = '2016-04-01T12:37:09'
2309
2310 for exp_tz, tzi in tzinfos:
2311 dt = dt_base.replace(tzinfo=tzi)
2312 exp = exp_base + exp_tz
2313 with self.subTest(tzi=tzi):
2314 assert dt.isoformat() == exp
2315
2316 def test_format(self):
2317 dt = self.theclass(2007, 9, 10, 4, 5, 1, 123)
2318 self.assertEqual(dt.__format__(''), str(dt))
2319
2320 with self.assertRaisesRegex(TypeError, 'must be str, not int'):
2321 dt.__format__(123)
2322
2323 # check that a derived class's __str__() gets called
2324 class A(self.theclass):
2325 def __str__(self):
2326 return 'A'
2327 a = A(2007, 9, 10, 4, 5, 1, 123)
2328 self.assertEqual(a.__format__(''), 'A')
2329
2330 # check that a derived class's strftime gets called
2331 class B(self.theclass):
2332 def strftime(self, format_spec):
2333 return 'B'
2334 b = B(2007, 9, 10, 4, 5, 1, 123)
2335 self.assertEqual(b.__format__(''), str(dt))
2336
2337 for fmt in ["m:%m d:%d y:%y",
2338 "m:%m d:%d y:%y H:%H M:%M S:%S",
2339 "%z %:z %Z",
2340 ]:
2341 self.assertEqual(dt.__format__(fmt), dt.strftime(fmt))
2342 self.assertEqual(a.__format__(fmt), dt.strftime(fmt))
2343 self.assertEqual(b.__format__(fmt), 'B')
2344
2345 def test_more_ctime(self):
2346 # Test fields that TestDate doesn't touch.
2347 import time
2348
2349 t = self.theclass(2002, 3, 2, 18, 3, 5, 123)
2350 self.assertEqual(t.ctime(), "Sat Mar 2 18:03:05 2002")
2351 # Oops! The next line fails on Win2K under MSVC 6, so it's commented
2352 # out. The difference is that t.ctime() produces " 2" for the day,
2353 # but platform ctime() produces "02" for the day. According to
2354 # C99, t.ctime() is correct here.
2355 # self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple())))
2356
2357 # So test a case where that difference doesn't matter.
2358 t = self.theclass(2002, 3, 22, 18, 3, 5, 123)
2359 self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple())))
2360
2361 def test_tz_independent_comparing(self):
2362 dt1 = self.theclass(2002, 3, 1, 9, 0, 0)
2363 dt2 = self.theclass(2002, 3, 1, 10, 0, 0)
2364 dt3 = self.theclass(2002, 3, 1, 9, 0, 0)
2365 self.assertEqual(dt1, dt3)
2366 self.assertTrue(dt2 > dt3)
2367
2368 # Make sure comparison doesn't forget microseconds, and isn't done
2369 # via comparing a float timestamp (an IEEE double doesn't have enough
2370 # precision to span microsecond resolution across years 1 through 9999,
2371 # so comparing via timestamp necessarily calls some distinct values
2372 # equal).
2373 dt1 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999998)
2374 us = timedelta(microseconds=1)
2375 dt2 = dt1 + us
2376 self.assertEqual(dt2 - dt1, us)
2377 self.assertTrue(dt1 < dt2)
2378
2379 def test_strftime_with_bad_tzname_replace(self):
2380 # verify ok if tzinfo.tzname().replace() returns a non-string
2381 class MyTzInfo(FixedOffset):
2382 def tzname(self, dt):
2383 class MyStr(str):
2384 def replace(self, *args):
2385 return None
2386 return MyStr('name')
2387 t = self.theclass(2005, 3, 2, 0, 0, 0, 0, MyTzInfo(3, 'name'))
2388 self.assertRaises(TypeError, t.strftime, '%Z')
2389
2390 def test_bad_constructor_arguments(self):
2391 # bad years
2392 self.theclass(MINYEAR, 1, 1) # no exception
2393 self.theclass(MAXYEAR, 1, 1) # no exception
2394 self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1)
2395 self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1)
2396 # bad months
2397 self.theclass(2000, 1, 1) # no exception
2398 self.theclass(2000, 12, 1) # no exception
2399 self.assertRaises(ValueError, self.theclass, 2000, 0, 1)
2400 self.assertRaises(ValueError, self.theclass, 2000, 13, 1)
2401 # bad days
2402 self.theclass(2000, 2, 29) # no exception
2403 self.theclass(2004, 2, 29) # no exception
2404 self.theclass(2400, 2, 29) # no exception
2405 self.assertRaises(ValueError, self.theclass, 2000, 2, 30)
2406 self.assertRaises(ValueError, self.theclass, 2001, 2, 29)
2407 self.assertRaises(ValueError, self.theclass, 2100, 2, 29)
2408 self.assertRaises(ValueError, self.theclass, 1900, 2, 29)
2409 self.assertRaises(ValueError, self.theclass, 2000, 1, 0)
2410 self.assertRaises(ValueError, self.theclass, 2000, 1, 32)
2411 # bad hours
2412 self.theclass(2000, 1, 31, 0) # no exception
2413 self.theclass(2000, 1, 31, 23) # no exception
2414 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, -1)
2415 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 24)
2416 # bad minutes
2417 self.theclass(2000, 1, 31, 23, 0) # no exception
2418 self.theclass(2000, 1, 31, 23, 59) # no exception
2419 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, -1)
2420 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 60)
2421 # bad seconds
2422 self.theclass(2000, 1, 31, 23, 59, 0) # no exception
2423 self.theclass(2000, 1, 31, 23, 59, 59) # no exception
2424 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, -1)
2425 self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, 60)
2426 # bad microseconds
2427 self.theclass(2000, 1, 31, 23, 59, 59, 0) # no exception
2428 self.theclass(2000, 1, 31, 23, 59, 59, 999999) # no exception
2429 self.assertRaises(ValueError, self.theclass,
2430 2000, 1, 31, 23, 59, 59, -1)
2431 self.assertRaises(ValueError, self.theclass,
2432 2000, 1, 31, 23, 59, 59,
2433 1000000)
2434 # bad fold
2435 self.assertRaises(ValueError, self.theclass,
2436 2000, 1, 31, fold=-1)
2437 self.assertRaises(ValueError, self.theclass,
2438 2000, 1, 31, fold=2)
2439 # Positional fold:
2440 self.assertRaises(TypeError, self.theclass,
2441 2000, 1, 31, 23, 59, 59, 0, None, 1)
2442
2443 def test_hash_equality(self):
2444 d = self.theclass(2000, 12, 31, 23, 30, 17)
2445 e = self.theclass(2000, 12, 31, 23, 30, 17)
2446 self.assertEqual(d, e)
2447 self.assertEqual(hash(d), hash(e))
2448
2449 dic = {d: 1}
2450 dic[e] = 2
2451 self.assertEqual(len(dic), 1)
2452 self.assertEqual(dic[d], 2)
2453 self.assertEqual(dic[e], 2)
2454
2455 d = self.theclass(2001, 1, 1, 0, 5, 17)
2456 e = self.theclass(2001, 1, 1, 0, 5, 17)
2457 self.assertEqual(d, e)
2458 self.assertEqual(hash(d), hash(e))
2459
2460 dic = {d: 1}
2461 dic[e] = 2
2462 self.assertEqual(len(dic), 1)
2463 self.assertEqual(dic[d], 2)
2464 self.assertEqual(dic[e], 2)
2465
2466 def test_computations(self):
2467 a = self.theclass(2002, 1, 31)
2468 b = self.theclass(1956, 1, 31)
2469 diff = a-b
2470 self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4)))
2471 self.assertEqual(diff.seconds, 0)
2472 self.assertEqual(diff.microseconds, 0)
2473 a = self.theclass(2002, 3, 2, 17, 6)
2474 millisec = timedelta(0, 0, 1000)
2475 hour = timedelta(0, 3600)
2476 day = timedelta(1)
2477 week = timedelta(7)
2478 self.assertEqual(a + hour, self.theclass(2002, 3, 2, 18, 6))
2479 self.assertEqual(hour + a, self.theclass(2002, 3, 2, 18, 6))
2480 self.assertEqual(a + 10*hour, self.theclass(2002, 3, 3, 3, 6))
2481 self.assertEqual(a - hour, self.theclass(2002, 3, 2, 16, 6))
2482 self.assertEqual(-hour + a, self.theclass(2002, 3, 2, 16, 6))
2483 self.assertEqual(a - hour, a + -hour)
2484 self.assertEqual(a - 20*hour, self.theclass(2002, 3, 1, 21, 6))
2485 self.assertEqual(a + day, self.theclass(2002, 3, 3, 17, 6))
2486 self.assertEqual(a - day, self.theclass(2002, 3, 1, 17, 6))
2487 self.assertEqual(a + week, self.theclass(2002, 3, 9, 17, 6))
2488 self.assertEqual(a - week, self.theclass(2002, 2, 23, 17, 6))
2489 self.assertEqual(a + 52*week, self.theclass(2003, 3, 1, 17, 6))
2490 self.assertEqual(a - 52*week, self.theclass(2001, 3, 3, 17, 6))
2491 self.assertEqual((a + week) - a, week)
2492 self.assertEqual((a + day) - a, day)
2493 self.assertEqual((a + hour) - a, hour)
2494 self.assertEqual((a + millisec) - a, millisec)
2495 self.assertEqual((a - week) - a, -week)
2496 self.assertEqual((a - day) - a, -day)
2497 self.assertEqual((a - hour) - a, -hour)
2498 self.assertEqual((a - millisec) - a, -millisec)
2499 self.assertEqual(a - (a + week), -week)
2500 self.assertEqual(a - (a + day), -day)
2501 self.assertEqual(a - (a + hour), -hour)
2502 self.assertEqual(a - (a + millisec), -millisec)
2503 self.assertEqual(a - (a - week), week)
2504 self.assertEqual(a - (a - day), day)
2505 self.assertEqual(a - (a - hour), hour)
2506 self.assertEqual(a - (a - millisec), millisec)
2507 self.assertEqual(a + (week + day + hour + millisec),
2508 self.theclass(2002, 3, 10, 18, 6, 0, 1000))
2509 self.assertEqual(a + (week + day + hour + millisec),
2510 (((a + week) + day) + hour) + millisec)
2511 self.assertEqual(a - (week + day + hour + millisec),
2512 self.theclass(2002, 2, 22, 16, 5, 59, 999000))
2513 self.assertEqual(a - (week + day + hour + millisec),
2514 (((a - week) - day) - hour) - millisec)
2515 # Add/sub ints or floats should be illegal
2516 for i in 1, 1.0:
2517 self.assertRaises(TypeError, lambda: a+i)
2518 self.assertRaises(TypeError, lambda: a-i)
2519 self.assertRaises(TypeError, lambda: i+a)
2520 self.assertRaises(TypeError, lambda: i-a)
2521
2522 # delta - datetime is senseless.
2523 self.assertRaises(TypeError, lambda: day - a)
2524 # mixing datetime and (delta or datetime) via * or // is senseless
2525 self.assertRaises(TypeError, lambda: day * a)
2526 self.assertRaises(TypeError, lambda: a * day)
2527 self.assertRaises(TypeError, lambda: day // a)
2528 self.assertRaises(TypeError, lambda: a // day)
2529 self.assertRaises(TypeError, lambda: a * a)
2530 self.assertRaises(TypeError, lambda: a // a)
2531 # datetime + datetime is senseless
2532 self.assertRaises(TypeError, lambda: a + a)
2533
2534 def test_pickling(self):
2535 args = 6, 7, 23, 20, 59, 1, 64**2
2536 orig = self.theclass(*args)
2537 for pickler, unpickler, proto in pickle_choices:
2538 green = pickler.dumps(orig, proto)
2539 derived = unpickler.loads(green)
2540 self.assertEqual(orig, derived)
2541 self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2))
2542
2543 def test_more_pickling(self):
2544 a = self.theclass(2003, 2, 7, 16, 48, 37, 444116)
2545 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2546 s = pickle.dumps(a, proto)
2547 b = pickle.loads(s)
2548 self.assertEqual(b.year, 2003)
2549 self.assertEqual(b.month, 2)
2550 self.assertEqual(b.day, 7)
2551
2552 def test_pickling_subclass_datetime(self):
2553 args = 6, 7, 23, 20, 59, 1, 64**2
2554 orig = SubclassDatetime(*args)
2555 for pickler, unpickler, proto in pickle_choices:
2556 green = pickler.dumps(orig, proto)
2557 derived = unpickler.loads(green)
2558 self.assertEqual(orig, derived)
2559 self.assertTrue(isinstance(derived, SubclassDatetime))
2560
2561 def test_compat_unpickle(self):
2562 tests = [
2563 b'cdatetime\ndatetime\n('
2564 b"S'\\x07\\xdf\\x0b\\x1b\\x14;\\x01\\x00\\x10\\x00'\ntR.",
2565
2566 b'cdatetime\ndatetime\n('
2567 b'U\n\x07\xdf\x0b\x1b\x14;\x01\x00\x10\x00tR.',
2568
2569 b'\x80\x02cdatetime\ndatetime\n'
2570 b'U\n\x07\xdf\x0b\x1b\x14;\x01\x00\x10\x00\x85R.',
2571 ]
2572 args = 2015, 11, 27, 20, 59, 1, 64**2
2573 expected = self.theclass(*args)
2574 for data in tests:
2575 for loads in pickle_loads:
2576 derived = loads(data, encoding='latin1')
2577 self.assertEqual(derived, expected)
2578
2579 def test_more_compare(self):
2580 # The test_compare() inherited from TestDate covers the error cases.
2581 # We just want to test lexicographic ordering on the members datetime
2582 # has that date lacks.
2583 args = [2000, 11, 29, 20, 58, 16, 999998]
2584 t1 = self.theclass(*args)
2585 t2 = self.theclass(*args)
2586 self.assertEqual(t1, t2)
2587 self.assertTrue(t1 <= t2)
2588 self.assertTrue(t1 >= t2)
2589 self.assertFalse(t1 != t2)
2590 self.assertFalse(t1 < t2)
2591 self.assertFalse(t1 > t2)
2592
2593 for i in range(len(args)):
2594 newargs = args[:]
2595 newargs[i] = args[i] + 1
2596 t2 = self.theclass(*newargs) # this is larger than t1
2597 self.assertTrue(t1 < t2)
2598 self.assertTrue(t2 > t1)
2599 self.assertTrue(t1 <= t2)
2600 self.assertTrue(t2 >= t1)
2601 self.assertTrue(t1 != t2)
2602 self.assertTrue(t2 != t1)
2603 self.assertFalse(t1 == t2)
2604 self.assertFalse(t2 == t1)
2605 self.assertFalse(t1 > t2)
2606 self.assertFalse(t2 < t1)
2607 self.assertFalse(t1 >= t2)
2608 self.assertFalse(t2 <= t1)
2609
2610
2611 # A helper for timestamp constructor tests.
2612 def verify_field_equality(self, expected, got):
2613 self.assertEqual(expected.tm_year, got.year)
2614 self.assertEqual(expected.tm_mon, got.month)
2615 self.assertEqual(expected.tm_mday, got.day)
2616 self.assertEqual(expected.tm_hour, got.hour)
2617 self.assertEqual(expected.tm_min, got.minute)
2618 self.assertEqual(expected.tm_sec, got.second)
2619
2620 def test_fromtimestamp(self):
2621 import time
2622
2623 ts = time.time()
2624 expected = time.localtime(ts)
2625 got = self.theclass.fromtimestamp(ts)
2626 self.verify_field_equality(expected, got)
2627
2628 def test_fromtimestamp_keyword_arg(self):
2629 import time
2630
2631 # gh-85432: The parameter was named "t" in the pure-Python impl.
2632 self.theclass.fromtimestamp(timestamp=time.time())
2633
2634 def test_utcfromtimestamp(self):
2635 import time
2636
2637 ts = time.time()
2638 expected = time.gmtime(ts)
2639 with self.assertWarns(DeprecationWarning):
2640 got = self.theclass.utcfromtimestamp(ts)
2641 self.verify_field_equality(expected, got)
2642
2643 # Run with US-style DST rules: DST begins 2 a.m. on second Sunday in
2644 # March (M3.2.0) and ends 2 a.m. on first Sunday in November (M11.1.0).
2645 @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0')
2646 def test_timestamp_naive(self):
2647 t = self.theclass(1970, 1, 1)
2648 self.assertEqual(t.timestamp(), 18000.0)
2649 t = self.theclass(1970, 1, 1, 1, 2, 3, 4)
2650 self.assertEqual(t.timestamp(),
2651 18000.0 + 3600 + 2*60 + 3 + 4*1e-6)
2652 # Missing hour
2653 t0 = self.theclass(2012, 3, 11, 2, 30)
2654 t1 = t0.replace(fold=1)
2655 self.assertEqual(self.theclass.fromtimestamp(t1.timestamp()),
2656 t0 - timedelta(hours=1))
2657 self.assertEqual(self.theclass.fromtimestamp(t0.timestamp()),
2658 t1 + timedelta(hours=1))
2659 # Ambiguous hour defaults to DST
2660 t = self.theclass(2012, 11, 4, 1, 30)
2661 self.assertEqual(self.theclass.fromtimestamp(t.timestamp()), t)
2662
2663 # Timestamp may raise an overflow error on some platforms
2664 # XXX: Do we care to support the first and last year?
2665 for t in [self.theclass(2,1,1), self.theclass(9998,12,12)]:
2666 try:
2667 s = t.timestamp()
2668 except OverflowError:
2669 pass
2670 else:
2671 self.assertEqual(self.theclass.fromtimestamp(s), t)
2672
2673 def test_timestamp_aware(self):
2674 t = self.theclass(1970, 1, 1, tzinfo=timezone.utc)
2675 self.assertEqual(t.timestamp(), 0.0)
2676 t = self.theclass(1970, 1, 1, 1, 2, 3, 4, tzinfo=timezone.utc)
2677 self.assertEqual(t.timestamp(),
2678 3600 + 2*60 + 3 + 4*1e-6)
2679 t = self.theclass(1970, 1, 1, 1, 2, 3, 4,
2680 tzinfo=timezone(timedelta(hours=-5), 'EST'))
2681 self.assertEqual(t.timestamp(),
2682 18000 + 3600 + 2*60 + 3 + 4*1e-6)
2683
2684 @support.run_with_tz('MSK-03') # Something east of Greenwich
2685 def test_microsecond_rounding(self):
2686 def utcfromtimestamp(*args, **kwargs):
2687 with self.assertWarns(DeprecationWarning):
2688 return self.theclass.utcfromtimestamp(*args, **kwargs)
2689
2690 for fts in [self.theclass.fromtimestamp,
2691 utcfromtimestamp]:
2692 zero = fts(0)
2693 self.assertEqual(zero.second, 0)
2694 self.assertEqual(zero.microsecond, 0)
2695 one = fts(1e-6)
2696 try:
2697 minus_one = fts(-1e-6)
2698 except OSError:
2699 # localtime(-1) and gmtime(-1) is not supported on Windows
2700 pass
2701 else:
2702 self.assertEqual(minus_one.second, 59)
2703 self.assertEqual(minus_one.microsecond, 999999)
2704
2705 t = fts(-1e-8)
2706 self.assertEqual(t, zero)
2707 t = fts(-9e-7)
2708 self.assertEqual(t, minus_one)
2709 t = fts(-1e-7)
2710 self.assertEqual(t, zero)
2711 t = fts(-1/2**7)
2712 self.assertEqual(t.second, 59)
2713 self.assertEqual(t.microsecond, 992188)
2714
2715 t = fts(1e-7)
2716 self.assertEqual(t, zero)
2717 t = fts(9e-7)
2718 self.assertEqual(t, one)
2719 t = fts(0.99999949)
2720 self.assertEqual(t.second, 0)
2721 self.assertEqual(t.microsecond, 999999)
2722 t = fts(0.9999999)
2723 self.assertEqual(t.second, 1)
2724 self.assertEqual(t.microsecond, 0)
2725 t = fts(1/2**7)
2726 self.assertEqual(t.second, 0)
2727 self.assertEqual(t.microsecond, 7812)
2728
2729 def test_timestamp_limits(self):
2730 with self.subTest("minimum UTC"):
2731 min_dt = self.theclass.min.replace(tzinfo=timezone.utc)
2732 min_ts = min_dt.timestamp()
2733
2734 # This test assumes that datetime.min == 0000-01-01T00:00:00.00
2735 # If that assumption changes, this value can change as well
2736 self.assertEqual(min_ts, -62135596800)
2737
2738 with self.subTest("maximum UTC"):
2739 # Zero out microseconds to avoid rounding issues
2740 max_dt = self.theclass.max.replace(tzinfo=timezone.utc,
2741 microsecond=0)
2742 max_ts = max_dt.timestamp()
2743
2744 # This test assumes that datetime.max == 9999-12-31T23:59:59.999999
2745 # If that assumption changes, this value can change as well
2746 self.assertEqual(max_ts, 253402300799.0)
2747
2748 def test_fromtimestamp_limits(self):
2749 try:
2750 self.theclass.fromtimestamp(-2**32 - 1)
2751 except (OSError, OverflowError):
2752 self.skipTest("Test not valid on this platform")
2753
2754 # XXX: Replace these with datetime.{min,max}.timestamp() when we solve
2755 # the issue with gh-91012
2756 min_dt = self.theclass.min + timedelta(days=1)
2757 min_ts = min_dt.timestamp()
2758
2759 max_dt = self.theclass.max.replace(microsecond=0)
2760 max_ts = ((self.theclass.max - timedelta(hours=23)).timestamp() +
2761 timedelta(hours=22, minutes=59, seconds=59).total_seconds())
2762
2763 for (test_name, ts, expected) in [
2764 ("minimum", min_ts, min_dt),
2765 ("maximum", max_ts, max_dt),
2766 ]:
2767 with self.subTest(test_name, ts=ts, expected=expected):
2768 actual = self.theclass.fromtimestamp(ts)
2769
2770 self.assertEqual(actual, expected)
2771
2772 # Test error conditions
2773 test_cases = [
2774 ("Too small by a little", min_ts - timedelta(days=1, hours=12).total_seconds()),
2775 ("Too small by a lot", min_ts - timedelta(days=400).total_seconds()),
2776 ("Too big by a little", max_ts + timedelta(days=1).total_seconds()),
2777 ("Too big by a lot", max_ts + timedelta(days=400).total_seconds()),
2778 ]
2779
2780 for test_name, ts in test_cases:
2781 with self.subTest(test_name, ts=ts):
2782 with self.assertRaises((ValueError, OverflowError)):
2783 # converting a Python int to C time_t can raise a
2784 # OverflowError, especially on 32-bit platforms.
2785 self.theclass.fromtimestamp(ts)
2786
2787 def test_utcfromtimestamp_limits(self):
2788 with self.assertWarns(DeprecationWarning):
2789 try:
2790 self.theclass.utcfromtimestamp(-2**32 - 1)
2791 except (OSError, OverflowError):
2792 self.skipTest("Test not valid on this platform")
2793
2794 min_dt = self.theclass.min.replace(tzinfo=timezone.utc)
2795 min_ts = min_dt.timestamp()
2796
2797 max_dt = self.theclass.max.replace(microsecond=0, tzinfo=timezone.utc)
2798 max_ts = max_dt.timestamp()
2799
2800 for (test_name, ts, expected) in [
2801 ("minimum", min_ts, min_dt.replace(tzinfo=None)),
2802 ("maximum", max_ts, max_dt.replace(tzinfo=None)),
2803 ]:
2804 with self.subTest(test_name, ts=ts, expected=expected):
2805 with self.assertWarns(DeprecationWarning):
2806 try:
2807 actual = self.theclass.utcfromtimestamp(ts)
2808 except (OSError, OverflowError) as exc:
2809 self.skipTest(str(exc))
2810
2811 self.assertEqual(actual, expected)
2812
2813 # Test error conditions
2814 test_cases = [
2815 ("Too small by a little", min_ts - 1),
2816 ("Too small by a lot", min_ts - timedelta(days=400).total_seconds()),
2817 ("Too big by a little", max_ts + 1),
2818 ("Too big by a lot", max_ts + timedelta(days=400).total_seconds()),
2819 ]
2820
2821 for test_name, ts in test_cases:
2822 with self.subTest(test_name, ts=ts):
2823 with self.assertRaises((ValueError, OverflowError)):
2824 with self.assertWarns(DeprecationWarning):
2825 # converting a Python int to C time_t can raise a
2826 # OverflowError, especially on 32-bit platforms.
2827 self.theclass.utcfromtimestamp(ts)
2828
2829 def test_insane_fromtimestamp(self):
2830 # It's possible that some platform maps time_t to double,
2831 # and that this test will fail there. This test should
2832 # exempt such platforms (provided they return reasonable
2833 # results!).
2834 for insane in -1e200, 1e200:
2835 self.assertRaises(OverflowError, self.theclass.fromtimestamp,
2836 insane)
2837
2838 def test_insane_utcfromtimestamp(self):
2839 # It's possible that some platform maps time_t to double,
2840 # and that this test will fail there. This test should
2841 # exempt such platforms (provided they return reasonable
2842 # results!).
2843 for insane in -1e200, 1e200:
2844 with self.assertWarns(DeprecationWarning):
2845 self.assertRaises(OverflowError, self.theclass.utcfromtimestamp,
2846 insane)
2847
2848 @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps")
2849 def test_negative_float_fromtimestamp(self):
2850 # The result is tz-dependent; at least test that this doesn't
2851 # fail (like it did before bug 1646728 was fixed).
2852 self.theclass.fromtimestamp(-1.05)
2853
2854 @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps")
2855 def test_negative_float_utcfromtimestamp(self):
2856 with self.assertWarns(DeprecationWarning):
2857 d = self.theclass.utcfromtimestamp(-1.05)
2858 self.assertEqual(d, self.theclass(1969, 12, 31, 23, 59, 58, 950000))
2859
2860 def test_utcnow(self):
2861 import time
2862
2863 # Call it a success if utcnow() and utcfromtimestamp() are within
2864 # a second of each other.
2865 tolerance = timedelta(seconds=1)
2866 for dummy in range(3):
2867 with self.assertWarns(DeprecationWarning):
2868 from_now = self.theclass.utcnow()
2869
2870 with self.assertWarns(DeprecationWarning):
2871 from_timestamp = self.theclass.utcfromtimestamp(time.time())
2872 if abs(from_timestamp - from_now) <= tolerance:
2873 break
2874 # Else try again a few times.
2875 self.assertLessEqual(abs(from_timestamp - from_now), tolerance)
2876
2877 def test_strptime(self):
2878 string = '2004-12-01 13:02:47.197'
2879 format = '%Y-%m-%d %H:%M:%S.%f'
2880 expected = _strptime._strptime_datetime_datetime(self.theclass, string,
2881 format)
2882 got = self.theclass.strptime(string, format)
2883 self.assertEqual(expected, got)
2884 self.assertIs(type(expected), self.theclass)
2885 self.assertIs(type(got), self.theclass)
2886
2887 # bpo-34482: Check that surrogates are handled properly.
2888 inputs = [
2889 ('2004-12-01\ud80013:02:47.197', '%Y-%m-%d\ud800%H:%M:%S.%f'),
2890 ('2004\ud80012-01 13:02:47.197', '%Y\ud800%m-%d %H:%M:%S.%f'),
2891 ('2004-12-01 13:02\ud80047.197', '%Y-%m-%d %H:%M\ud800%S.%f'),
2892 ]
2893 for string, format in inputs:
2894 with self.subTest(string=string, format=format):
2895 expected = _strptime._strptime_datetime_datetime(self.theclass,
2896 string, format)
2897 got = self.theclass.strptime(string, format)
2898 self.assertEqual(expected, got)
2899
2900 strptime = self.theclass.strptime
2901
2902 self.assertEqual(strptime("+0002", "%z").utcoffset(), 2 * MINUTE)
2903 self.assertEqual(strptime("-0002", "%z").utcoffset(), -2 * MINUTE)
2904 self.assertEqual(
2905 strptime("-00:02:01.000003", "%z").utcoffset(),
2906 -timedelta(minutes=2, seconds=1, microseconds=3)
2907 )
2908 # Only local timezone and UTC are supported
2909 for tzseconds, tzname in ((0, 'UTC'), (0, 'GMT'),
2910 (-_time.timezone, _time.tzname[0])):
2911 if tzseconds < 0:
2912 sign = '-'
2913 seconds = -tzseconds
2914 else:
2915 sign ='+'
2916 seconds = tzseconds
2917 hours, minutes = divmod(seconds//60, 60)
2918 dtstr = "{}{:02d}{:02d} {}".format(sign, hours, minutes, tzname)
2919 dt = strptime(dtstr, "%z %Z")
2920 self.assertEqual(dt.utcoffset(), timedelta(seconds=tzseconds))
2921 self.assertEqual(dt.tzname(), tzname)
2922 # Can produce inconsistent datetime
2923 dtstr, fmt = "+1234 UTC", "%z %Z"
2924 dt = strptime(dtstr, fmt)
2925 self.assertEqual(dt.utcoffset(), 12 * HOUR + 34 * MINUTE)
2926 self.assertEqual(dt.tzname(), 'UTC')
2927 # yet will roundtrip
2928 self.assertEqual(dt.strftime(fmt), dtstr)
2929
2930 # Produce naive datetime if no %z is provided
2931 self.assertEqual(strptime("UTC", "%Z").tzinfo, None)
2932
2933 with self.assertRaises(ValueError): strptime("-2400", "%z")
2934 with self.assertRaises(ValueError): strptime("-000", "%z")
2935 with self.assertRaises(ValueError): strptime("z", "%z")
2936
2937 def test_strptime_single_digit(self):
2938 # bpo-34903: Check that single digit dates and times are allowed.
2939
2940 strptime = self.theclass.strptime
2941
2942 with self.assertRaises(ValueError):
2943 # %y does require two digits.
2944 newdate = strptime('01/02/3 04:05:06', '%d/%m/%y %H:%M:%S')
2945 dt1 = self.theclass(2003, 2, 1, 4, 5, 6)
2946 dt2 = self.theclass(2003, 1, 2, 4, 5, 6)
2947 dt3 = self.theclass(2003, 2, 1, 0, 0, 0)
2948 dt4 = self.theclass(2003, 1, 25, 0, 0, 0)
2949 inputs = [
2950 ('%d', '1/02/03 4:5:6', '%d/%m/%y %H:%M:%S', dt1),
2951 ('%m', '01/2/03 4:5:6', '%d/%m/%y %H:%M:%S', dt1),
2952 ('%H', '01/02/03 4:05:06', '%d/%m/%y %H:%M:%S', dt1),
2953 ('%M', '01/02/03 04:5:06', '%d/%m/%y %H:%M:%S', dt1),
2954 ('%S', '01/02/03 04:05:6', '%d/%m/%y %H:%M:%S', dt1),
2955 ('%j', '2/03 04am:05:06', '%j/%y %I%p:%M:%S',dt2),
2956 ('%I', '02/03 4am:05:06', '%j/%y %I%p:%M:%S',dt2),
2957 ('%w', '6/04/03', '%w/%U/%y', dt3),
2958 # %u requires a single digit.
2959 ('%W', '6/4/2003', '%u/%W/%Y', dt3),
2960 ('%V', '6/4/2003', '%u/%V/%G', dt4),
2961 ]
2962 for reason, string, format, target in inputs:
2963 reason = 'test single digit ' + reason
2964 with self.subTest(reason=reason,
2965 string=string,
2966 format=format,
2967 target=target):
2968 newdate = strptime(string, format)
2969 self.assertEqual(newdate, target, msg=reason)
2970
2971 @warnings_helper.ignore_warnings(category=DeprecationWarning)
2972 def test_strptime_leap_year(self):
2973 # GH-70647: warns if parsing a format with a day and no year.
2974 with self.assertRaises(ValueError):
2975 # The existing behavior that GH-70647 seeks to change.
2976 self.theclass.strptime('02-29', '%m-%d')
2977 with self.assertWarnsRegex(DeprecationWarning,
2978 r'.*day of month without a year.*'):
2979 self.theclass.strptime('03-14.159265', '%m-%d.%f')
2980 with self._assertNotWarns(DeprecationWarning):
2981 self.theclass.strptime('20-03-14.159265', '%y-%m-%d.%f')
2982 with self._assertNotWarns(DeprecationWarning):
2983 self.theclass.strptime('02-29,2024', '%m-%d,%Y')
2984
2985 def test_more_timetuple(self):
2986 # This tests fields beyond those tested by the TestDate.test_timetuple.
2987 t = self.theclass(2004, 12, 31, 6, 22, 33)
2988 self.assertEqual(t.timetuple(), (2004, 12, 31, 6, 22, 33, 4, 366, -1))
2989 self.assertEqual(t.timetuple(),
2990 (t.year, t.month, t.day,
2991 t.hour, t.minute, t.second,
2992 t.weekday(),
2993 t.toordinal() - date(t.year, 1, 1).toordinal() + 1,
2994 -1))
2995 tt = t.timetuple()
2996 self.assertEqual(tt.tm_year, t.year)
2997 self.assertEqual(tt.tm_mon, t.month)
2998 self.assertEqual(tt.tm_mday, t.day)
2999 self.assertEqual(tt.tm_hour, t.hour)
3000 self.assertEqual(tt.tm_min, t.minute)
3001 self.assertEqual(tt.tm_sec, t.second)
3002 self.assertEqual(tt.tm_wday, t.weekday())
3003 self.assertEqual(tt.tm_yday, t.toordinal() -
3004 date(t.year, 1, 1).toordinal() + 1)
3005 self.assertEqual(tt.tm_isdst, -1)
3006
3007 def test_more_strftime(self):
3008 # This tests fields beyond those tested by the TestDate.test_strftime.
3009 t = self.theclass(2004, 12, 31, 6, 22, 33, 47)
3010 self.assertEqual(t.strftime("%m %d %y %f %S %M %H %j"),
3011 "12 31 04 000047 33 22 06 366")
3012 for (s, us), z in [((33, 123), "33.000123"), ((33, 0), "33"),]:
3013 tz = timezone(-timedelta(hours=2, seconds=s, microseconds=us))
3014 t = t.replace(tzinfo=tz)
3015 self.assertEqual(t.strftime("%z"), "-0200" + z)
3016 self.assertEqual(t.strftime("%:z"), "-02:00:" + z)
3017
3018 def test_strftime_special(self):
3019 t = self.theclass(2004, 12, 31, 6, 22, 33, 47)
3020 s1 = t.strftime('%c')
3021 s2 = t.strftime('%B')
3022 # gh-52551, gh-78662: Unicode strings should pass through strftime,
3023 # independently from locale.
3024 self.assertEqual(t.strftime('\U0001f40d'), '\U0001f40d')
3025 self.assertEqual(t.strftime('\U0001f4bb%c\U0001f40d%B'), f'\U0001f4bb{s1}\U0001f40d{s2}')
3026 self.assertEqual(t.strftime('%c\U0001f4bb%B\U0001f40d'), f'{s1}\U0001f4bb{s2}\U0001f40d')
3027 # Lone surrogates should pass through.
3028 self.assertEqual(t.strftime('\ud83d'), '\ud83d')
3029 self.assertEqual(t.strftime('\udc0d'), '\udc0d')
3030 self.assertEqual(t.strftime('\ud83d%c\udc0d%B'), f'\ud83d{s1}\udc0d{s2}')
3031 self.assertEqual(t.strftime('%c\ud83d%B\udc0d'), f'{s1}\ud83d{s2}\udc0d')
3032 self.assertEqual(t.strftime('%c\udc0d%B\ud83d'), f'{s1}\udc0d{s2}\ud83d')
3033 # Surrogate pairs should not recombine.
3034 self.assertEqual(t.strftime('\ud83d\udc0d'), '\ud83d\udc0d')
3035 self.assertEqual(t.strftime('%c\ud83d\udc0d%B'), f'{s1}\ud83d\udc0d{s2}')
3036 # Surrogate-escaped bytes should not recombine.
3037 self.assertEqual(t.strftime('\udcf0\udc9f\udc90\udc8d'), '\udcf0\udc9f\udc90\udc8d')
3038 self.assertEqual(t.strftime('%c\udcf0\udc9f\udc90\udc8d%B'), f'{s1}\udcf0\udc9f\udc90\udc8d{s2}')
3039 # gh-124531: The null character should not terminate the format string.
3040 self.assertEqual(t.strftime('\0'), '\0')
3041 self.assertEqual(t.strftime('\0'*1000), '\0'*1000)
3042 self.assertEqual(t.strftime('\0%c\0%B'), f'\0{s1}\0{s2}')
3043 self.assertEqual(t.strftime('%c\0%B\0'), f'{s1}\0{s2}\0')
3044
3045 def test_extract(self):
3046 dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
3047 self.assertEqual(dt.date(), date(2002, 3, 4))
3048 self.assertEqual(dt.time(), time(18, 45, 3, 1234))
3049
3050 def test_combine(self):
3051 d = date(2002, 3, 4)
3052 t = time(18, 45, 3, 1234)
3053 expected = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
3054 combine = self.theclass.combine
3055 dt = combine(d, t)
3056 self.assertEqual(dt, expected)
3057
3058 dt = combine(time=t, date=d)
3059 self.assertEqual(dt, expected)
3060
3061 self.assertEqual(d, dt.date())
3062 self.assertEqual(t, dt.time())
3063 self.assertEqual(dt, combine(dt.date(), dt.time()))
3064
3065 self.assertRaises(TypeError, combine) # need an arg
3066 self.assertRaises(TypeError, combine, d) # need two args
3067 self.assertRaises(TypeError, combine, t, d) # args reversed
3068 self.assertRaises(TypeError, combine, d, t, 1) # wrong tzinfo type
3069 self.assertRaises(TypeError, combine, d, t, 1, 2) # too many args
3070 self.assertRaises(TypeError, combine, "date", "time") # wrong types
3071 self.assertRaises(TypeError, combine, d, "time") # wrong type
3072 self.assertRaises(TypeError, combine, "date", t) # wrong type
3073
3074 # tzinfo= argument
3075 dt = combine(d, t, timezone.utc)
3076 self.assertIs(dt.tzinfo, timezone.utc)
3077 dt = combine(d, t, tzinfo=timezone.utc)
3078 self.assertIs(dt.tzinfo, timezone.utc)
3079 t = time()
3080 dt = combine(dt, t)
3081 self.assertEqual(dt.date(), d)
3082 self.assertEqual(dt.time(), t)
3083
3084 def test_replace(self):
3085 cls = self.theclass
3086 args = [1, 2, 3, 4, 5, 6, 7]
3087 base = cls(*args)
3088 self.assertEqual(base.replace(), base)
3089 self.assertEqual(copy.replace(base), base)
3090
3091 changes = (("year", 2),
3092 ("month", 3),
3093 ("day", 4),
3094 ("hour", 5),
3095 ("minute", 6),
3096 ("second", 7),
3097 ("microsecond", 8))
3098 for i, (name, newval) in enumerate(changes):
3099 newargs = args[:]
3100 newargs[i] = newval
3101 expected = cls(*newargs)
3102 self.assertEqual(base.replace(**{name: newval}), expected)
3103 self.assertEqual(copy.replace(base, **{name: newval}), expected)
3104
3105 # Out of bounds.
3106 base = cls(2000, 2, 29)
3107 self.assertRaises(ValueError, base.replace, year=2001)
3108 self.assertRaises(ValueError, copy.replace, base, year=2001)
3109
3110 @support.run_with_tz('EDT4')
3111 def test_astimezone(self):
3112 dt = self.theclass.now()
3113 f = FixedOffset(44, "0044")
3114 dt_utc = dt.replace(tzinfo=timezone(timedelta(hours=-4), 'EDT'))
3115 self.assertEqual(dt.astimezone(), dt_utc) # naive
3116 self.assertRaises(TypeError, dt.astimezone, f, f) # too many args
3117 self.assertRaises(TypeError, dt.astimezone, dt) # arg wrong type
3118 dt_f = dt.replace(tzinfo=f) + timedelta(hours=4, minutes=44)
3119 self.assertEqual(dt.astimezone(f), dt_f) # naive
3120 self.assertEqual(dt.astimezone(tz=f), dt_f) # naive
3121
3122 class Bogus(tzinfo):
3123 def utcoffset(self, dt): return None
3124 def dst(self, dt): return timedelta(0)
3125 bog = Bogus()
3126 self.assertRaises(ValueError, dt.astimezone, bog) # naive
3127 self.assertEqual(dt.replace(tzinfo=bog).astimezone(f), dt_f)
3128
3129 class AlsoBogus(tzinfo):
3130 def utcoffset(self, dt): return timedelta(0)
3131 def dst(self, dt): return None
3132 alsobog = AlsoBogus()
3133 self.assertRaises(ValueError, dt.astimezone, alsobog) # also naive
3134
3135 class Broken(tzinfo):
3136 def utcoffset(self, dt): return 1
3137 def dst(self, dt): return 1
3138 broken = Broken()
3139 dt_broken = dt.replace(tzinfo=broken)
3140 with self.assertRaises(TypeError):
3141 dt_broken.astimezone()
3142
3143 def test_subclass_datetime(self):
3144
3145 class C(self.theclass):
3146 theAnswer = 42
3147
3148 def __new__(cls, *args, **kws):
3149 temp = kws.copy()
3150 extra = temp.pop('extra')
3151 result = self.theclass.__new__(cls, *args, **temp)
3152 result.extra = extra
3153 return result
3154
3155 def newmeth(self, start):
3156 return start + self.year + self.month + self.second
3157
3158 args = 2003, 4, 14, 12, 13, 41
3159
3160 dt1 = self.theclass(*args)
3161 dt2 = C(*args, **{'extra': 7})
3162
3163 self.assertEqual(dt2.__class__, C)
3164 self.assertEqual(dt2.theAnswer, 42)
3165 self.assertEqual(dt2.extra, 7)
3166 self.assertEqual(dt1.toordinal(), dt2.toordinal())
3167 self.assertEqual(dt2.newmeth(-7), dt1.year + dt1.month +
3168 dt1.second - 7)
3169
3170 def test_subclass_alternate_constructors_datetime(self):
3171 # Test that alternate constructors call the constructor
3172 class DateTimeSubclass(self.theclass):
3173 def __new__(cls, *args, **kwargs):
3174 result = self.theclass.__new__(cls, *args, **kwargs)
3175 result.extra = 7
3176
3177 return result
3178
3179 args = (2003, 4, 14, 12, 30, 15, 123456)
3180 d_isoformat = '2003-04-14T12:30:15.123456' # Equivalent isoformat()
3181 utc_ts = 1050323415.123456 # UTC timestamp
3182
3183 base_d = DateTimeSubclass(*args)
3184 self.assertIsInstance(base_d, DateTimeSubclass)
3185 self.assertEqual(base_d.extra, 7)
3186
3187 # Timestamp depends on time zone, so we'll calculate the equivalent here
3188 ts = base_d.timestamp()
3189
3190 test_cases = [
3191 ('fromtimestamp', (ts,), base_d),
3192 # See https://bugs.python.org/issue32417
3193 ('fromtimestamp', (ts, timezone.utc),
3194 base_d.astimezone(timezone.utc)),
3195 ('utcfromtimestamp', (utc_ts,), base_d),
3196 ('fromisoformat', (d_isoformat,), base_d),
3197 ('strptime', (d_isoformat, '%Y-%m-%dT%H:%M:%S.%f'), base_d),
3198 ('combine', (date(*args[0:3]), time(*args[3:])), base_d),
3199 ]
3200
3201 for constr_name, constr_args, expected in test_cases:
3202 for base_obj in (DateTimeSubclass, base_d):
3203 # Test both the classmethod and method
3204 with self.subTest(base_obj_type=type(base_obj),
3205 constr_name=constr_name):
3206 constructor = getattr(base_obj, constr_name)
3207
3208 if constr_name == "utcfromtimestamp":
3209 with self.assertWarns(DeprecationWarning):
3210 dt = constructor(*constr_args)
3211 else:
3212 dt = constructor(*constr_args)
3213
3214 # Test that it creates the right subclass
3215 self.assertIsInstance(dt, DateTimeSubclass)
3216
3217 # Test that it's equal to the base object
3218 self.assertEqual(dt, expected)
3219
3220 # Test that it called the constructor
3221 self.assertEqual(dt.extra, 7)
3222
3223 def test_subclass_now(self):
3224 # Test that alternate constructors call the constructor
3225 class DateTimeSubclass(self.theclass):
3226 def __new__(cls, *args, **kwargs):
3227 result = self.theclass.__new__(cls, *args, **kwargs)
3228 result.extra = 7
3229
3230 return result
3231
3232 test_cases = [
3233 ('now', 'now', {}),
3234 ('utcnow', 'utcnow', {}),
3235 ('now_utc', 'now', {'tz': timezone.utc}),
3236 ('now_fixed', 'now', {'tz': timezone(timedelta(hours=-5), "EST")}),
3237 ]
3238
3239 for name, meth_name, kwargs in test_cases:
3240 with self.subTest(name):
3241 constr = getattr(DateTimeSubclass, meth_name)
3242 if meth_name == "utcnow":
3243 with self.assertWarns(DeprecationWarning):
3244 dt = constr(**kwargs)
3245 else:
3246 dt = constr(**kwargs)
3247
3248 self.assertIsInstance(dt, DateTimeSubclass)
3249 self.assertEqual(dt.extra, 7)
3250
3251 def test_subclass_replace_fold(self):
3252 class DateTimeSubclass(self.theclass):
3253 pass
3254
3255 dt = DateTimeSubclass(2012, 1, 1)
3256 dt2 = DateTimeSubclass(2012, 1, 1, fold=1)
3257
3258 test_cases = [
3259 ('self.replace', dt.replace(year=2013), 0),
3260 ('self.replace', dt2.replace(year=2013), 1),
3261 ('copy.replace', copy.replace(dt, year=2013), 0),
3262 ('copy.replace', copy.replace(dt2, year=2013), 1),
3263 ]
3264
3265 for name, res, fold in test_cases:
3266 with self.subTest(name, fold=fold):
3267 self.assertIs(type(res), DateTimeSubclass)
3268 self.assertEqual(res.year, 2013)
3269 self.assertEqual(res.fold, fold)
3270
3271 def test_valuerror_messages(self):
3272 pattern = re.compile(
3273 r"(year|month|day|hour|minute|second) must "
3274 r"be in \d+\.\.\d+, not \d+"
3275 )
3276 test_cases = [
3277 (2009, 4, 1, 12, 30, 90), # Second out of range
3278 (2009, 4, 1, 12, 90, 45), # Minute out of range
3279 (2009, 4, 1, 25, 30, 45), # Hour out of range
3280 (2009, 13, 1, 24, 0, 0), # Month out of range
3281 (9999, 12, 31, 24, 0, 0), # Year out of range
3282 ]
3283 for case in test_cases:
3284 with self.subTest(case):
3285 with self.assertRaisesRegex(ValueError, pattern):
3286 self.theclass(*case)
3287
3288 # days out of range have their own error message, see issue 70647
3289 with self.assertRaises(ValueError) as msg:
3290 self.theclass(2009, 4, 32, 24, 0, 0)
3291 self.assertIn(f"day 32 must be in range 1..30 for month 4 in year 2009", str(msg.exception))
3292
3293 def test_fromisoformat_datetime(self):
3294 # Test that isoformat() is reversible
3295 base_dates = [
3296 (1, 1, 1),
3297 (1900, 1, 1),
3298 (2004, 11, 12),
3299 (2017, 5, 30)
3300 ]
3301
3302 base_times = [
3303 (0, 0, 0, 0),
3304 (0, 0, 0, 241000),
3305 (0, 0, 0, 234567),
3306 (12, 30, 45, 234567)
3307 ]
3308
3309 separators = [' ', 'T']
3310
3311 tzinfos = [None, timezone.utc,
3312 timezone(timedelta(hours=-5)),
3313 timezone(timedelta(hours=2))]
3314
3315 dts = [self.theclass(*date_tuple, *time_tuple, tzinfo=tzi)
3316 for date_tuple in base_dates
3317 for time_tuple in base_times
3318 for tzi in tzinfos]
3319
3320 for dt in dts:
3321 for sep in separators:
3322 dtstr = dt.isoformat(sep=sep)
3323
3324 with self.subTest(dtstr=dtstr):
3325 dt_rt = self.theclass.fromisoformat(dtstr)
3326 self.assertEqual(dt, dt_rt)
3327
3328 def test_fromisoformat_timezone(self):
3329 base_dt = self.theclass(2014, 12, 30, 12, 30, 45, 217456)
3330
3331 tzoffsets = [
3332 timedelta(hours=5), timedelta(hours=2),
3333 timedelta(hours=6, minutes=27),
3334 timedelta(hours=12, minutes=32, seconds=30),
3335 timedelta(hours=2, minutes=4, seconds=9, microseconds=123456)
3336 ]
3337
3338 tzoffsets += [-1 * td for td in tzoffsets]
3339
3340 tzinfos = [None, timezone.utc,
3341 timezone(timedelta(hours=0))]
3342
3343 tzinfos += [timezone(td) for td in tzoffsets]
3344
3345 for tzi in tzinfos:
3346 dt = base_dt.replace(tzinfo=tzi)
3347 dtstr = dt.isoformat()
3348
3349 with self.subTest(tstr=dtstr):
3350 dt_rt = self.theclass.fromisoformat(dtstr)
3351 assert dt == dt_rt, dt_rt
3352
3353 def test_fromisoformat_separators(self):
3354 separators = [
3355 ' ', 'T', '\u007f', # 1-bit widths
3356 '\u0080', 'ʁ', # 2-bit widths
3357 'ᛇ', '時', # 3-bit widths
3358 '🐍', # 4-bit widths
3359 '\ud800', # bpo-34454: Surrogate code point
3360 ]
3361
3362 for sep in separators:
3363 dt = self.theclass(2018, 1, 31, 23, 59, 47, 124789)
3364 dtstr = dt.isoformat(sep=sep)
3365
3366 with self.subTest(dtstr=dtstr):
3367 dt_rt = self.theclass.fromisoformat(dtstr)
3368 self.assertEqual(dt, dt_rt)
3369
3370 def test_fromisoformat_ambiguous(self):
3371 # Test strings like 2018-01-31+12:15 (where +12:15 is not a time zone)
3372 separators = ['+', '-']
3373 for sep in separators:
3374 dt = self.theclass(2018, 1, 31, 12, 15)
3375 dtstr = dt.isoformat(sep=sep)
3376
3377 with self.subTest(dtstr=dtstr):
3378 dt_rt = self.theclass.fromisoformat(dtstr)
3379 self.assertEqual(dt, dt_rt)
3380
3381 def test_fromisoformat_timespecs(self):
3382 datetime_bases = [
3383 (2009, 12, 4, 8, 17, 45, 123456),
3384 (2009, 12, 4, 8, 17, 45, 0)]
3385
3386 tzinfos = [None, timezone.utc,
3387 timezone(timedelta(hours=-5)),
3388 timezone(timedelta(hours=2)),
3389 timezone(timedelta(hours=6, minutes=27))]
3390
3391 timespecs = ['hours', 'minutes', 'seconds',
3392 'milliseconds', 'microseconds']
3393
3394 for ip, ts in enumerate(timespecs):
3395 for tzi in tzinfos:
3396 for dt_tuple in datetime_bases:
3397 if ts == 'milliseconds':
3398 new_microseconds = 1000 * (dt_tuple[6] // 1000)
3399 dt_tuple = dt_tuple[0:6] + (new_microseconds,)
3400
3401 dt = self.theclass(*(dt_tuple[0:(4 + ip)]), tzinfo=tzi)
3402 dtstr = dt.isoformat(timespec=ts)
3403 with self.subTest(dtstr=dtstr):
3404 dt_rt = self.theclass.fromisoformat(dtstr)
3405 self.assertEqual(dt, dt_rt)
3406
3407 def test_fromisoformat_datetime_examples(self):
3408 UTC = timezone.utc
3409 BST = timezone(timedelta(hours=1), 'BST')
3410 EST = timezone(timedelta(hours=-5), 'EST')
3411 EDT = timezone(timedelta(hours=-4), 'EDT')
3412 examples = [
3413 ('2025-01-02', self.theclass(2025, 1, 2, 0, 0)),
3414 ('2025-01-02T03', self.theclass(2025, 1, 2, 3, 0)),
3415 ('2025-01-02T03:04', self.theclass(2025, 1, 2, 3, 4)),
3416 ('2025-01-02T0304', self.theclass(2025, 1, 2, 3, 4)),
3417 ('2025-01-02T03:04:05', self.theclass(2025, 1, 2, 3, 4, 5)),
3418 ('2025-01-02T030405', self.theclass(2025, 1, 2, 3, 4, 5)),
3419 ('2025-01-02T03:04:05.6',
3420 self.theclass(2025, 1, 2, 3, 4, 5, 600000)),
3421 ('2025-01-02T03:04:05,6',
3422 self.theclass(2025, 1, 2, 3, 4, 5, 600000)),
3423 ('2025-01-02T03:04:05.678',
3424 self.theclass(2025, 1, 2, 3, 4, 5, 678000)),
3425 ('2025-01-02T03:04:05.678901',
3426 self.theclass(2025, 1, 2, 3, 4, 5, 678901)),
3427 ('2025-01-02T03:04:05,678901',
3428 self.theclass(2025, 1, 2, 3, 4, 5, 678901)),
3429 ('2025-01-02T030405.678901',
3430 self.theclass(2025, 1, 2, 3, 4, 5, 678901)),
3431 ('2025-01-02T030405,678901',
3432 self.theclass(2025, 1, 2, 3, 4, 5, 678901)),
3433 ('2025-01-02T03:04:05.6789010',
3434 self.theclass(2025, 1, 2, 3, 4, 5, 678901)),
3435 ('2009-04-19T03:15:45.2345',
3436 self.theclass(2009, 4, 19, 3, 15, 45, 234500)),
3437 ('2009-04-19T03:15:45.1234567',
3438 self.theclass(2009, 4, 19, 3, 15, 45, 123456)),
3439 ('2025-01-02T03:04:05,678',
3440 self.theclass(2025, 1, 2, 3, 4, 5, 678000)),
3441 ('20250102', self.theclass(2025, 1, 2, 0, 0)),
3442 ('20250102T03', self.theclass(2025, 1, 2, 3, 0)),
3443 ('20250102T03:04', self.theclass(2025, 1, 2, 3, 4)),
3444 ('20250102T03:04:05', self.theclass(2025, 1, 2, 3, 4, 5)),
3445 ('20250102T030405', self.theclass(2025, 1, 2, 3, 4, 5)),
3446 ('20250102T03:04:05.6',
3447 self.theclass(2025, 1, 2, 3, 4, 5, 600000)),
3448 ('20250102T03:04:05,6',
3449 self.theclass(2025, 1, 2, 3, 4, 5, 600000)),
3450 ('20250102T03:04:05.678',
3451 self.theclass(2025, 1, 2, 3, 4, 5, 678000)),
3452 ('20250102T03:04:05,678',
3453 self.theclass(2025, 1, 2, 3, 4, 5, 678000)),
3454 ('20250102T03:04:05.678901',
3455 self.theclass(2025, 1, 2, 3, 4, 5, 678901)),
3456 ('20250102T030405.678901',
3457 self.theclass(2025, 1, 2, 3, 4, 5, 678901)),
3458 ('20250102T030405,678901',
3459 self.theclass(2025, 1, 2, 3, 4, 5, 678901)),
3460 ('20250102T030405.6789010',
3461 self.theclass(2025, 1, 2, 3, 4, 5, 678901)),
3462 ('2022W01', self.theclass(2022, 1, 3)),
3463 ('2022W52520', self.theclass(2022, 12, 26, 20, 0)),
3464 ('2022W527520', self.theclass(2023, 1, 1, 20, 0)),
3465 ('2026W01516', self.theclass(2025, 12, 29, 16, 0)),
3466 ('2026W013516', self.theclass(2025, 12, 31, 16, 0)),
3467 ('2025W01503', self.theclass(2024, 12, 30, 3, 0)),
3468 ('2025W014503', self.theclass(2025, 1, 2, 3, 0)),
3469 ('2025W01512', self.theclass(2024, 12, 30, 12, 0)),
3470 ('2025W014512', self.theclass(2025, 1, 2, 12, 0)),
3471 ('2025W014T121431', self.theclass(2025, 1, 2, 12, 14, 31)),
3472 ('2026W013T162100', self.theclass(2025, 12, 31, 16, 21)),
3473 ('2026W013 162100', self.theclass(2025, 12, 31, 16, 21)),
3474 ('2022W527T202159', self.theclass(2023, 1, 1, 20, 21, 59)),
3475 ('2022W527 202159', self.theclass(2023, 1, 1, 20, 21, 59)),
3476 ('2025W014 121431', self.theclass(2025, 1, 2, 12, 14, 31)),
3477 ('2025W014T030405', self.theclass(2025, 1, 2, 3, 4, 5)),
3478 ('2025W014 030405', self.theclass(2025, 1, 2, 3, 4, 5)),
3479 ('2020-W53-6T03:04:05', self.theclass(2021, 1, 2, 3, 4, 5)),
3480 ('2020W537 03:04:05', self.theclass(2021, 1, 3, 3, 4, 5)),
3481 ('2025-W01-4T03:04:05', self.theclass(2025, 1, 2, 3, 4, 5)),
3482 ('2025-W01-4T03:04:05.678901',
3483 self.theclass(2025, 1, 2, 3, 4, 5, 678901)),
3484 ('2025-W01-4T12:14:31', self.theclass(2025, 1, 2, 12, 14, 31)),
3485 ('2025-W01-4T12:14:31.012345',
3486 self.theclass(2025, 1, 2, 12, 14, 31, 12345)),
3487 ('2026-W01-3T16:21:00', self.theclass(2025, 12, 31, 16, 21)),
3488 ('2026-W01-3T16:21:00.000000', self.theclass(2025, 12, 31, 16, 21)),
3489 ('2022-W52-7T20:21:59',
3490 self.theclass(2023, 1, 1, 20, 21, 59)),
3491 ('2022-W52-7T20:21:59.999999',
3492 self.theclass(2023, 1, 1, 20, 21, 59, 999999)),
3493 ('2025-W01003+00',
3494 self.theclass(2024, 12, 30, 3, 0, tzinfo=UTC)),
3495 ('2025-01-02T03:04:05+00',
3496 self.theclass(2025, 1, 2, 3, 4, 5, tzinfo=UTC)),
3497 ('2025-01-02T03:04:05Z',
3498 self.theclass(2025, 1, 2, 3, 4, 5, tzinfo=UTC)),
3499 ('2025-01-02003:04:05,6+00:00:00.00',
3500 self.theclass(2025, 1, 2, 3, 4, 5, 600000, tzinfo=UTC)),
3501 ('2000-01-01T00+21',
3502 self.theclass(2000, 1, 1, 0, 0, tzinfo=timezone(timedelta(hours=21)))),
3503 ('2025-01-02T03:05:06+0300',
3504 self.theclass(2025, 1, 2, 3, 5, 6,
3505 tzinfo=timezone(timedelta(hours=3)))),
3506 ('2025-01-02T03:05:06-0300',
3507 self.theclass(2025, 1, 2, 3, 5, 6,
3508 tzinfo=timezone(timedelta(hours=-3)))),
3509 ('2025-01-02T03:04:05+0000',
3510 self.theclass(2025, 1, 2, 3, 4, 5, tzinfo=UTC)),
3511 ('2025-01-02T03:05:06+03',
3512 self.theclass(2025, 1, 2, 3, 5, 6,
3513 tzinfo=timezone(timedelta(hours=3)))),
3514 ('2025-01-02T03:05:06-03',
3515 self.theclass(2025, 1, 2, 3, 5, 6,
3516 tzinfo=timezone(timedelta(hours=-3)))),
3517 ('2020-01-01T03:05:07.123457-05:00',
3518 self.theclass(2020, 1, 1, 3, 5, 7, 123457, tzinfo=EST)),
3519 ('2020-01-01T03:05:07.123457-0500',
3520 self.theclass(2020, 1, 1, 3, 5, 7, 123457, tzinfo=EST)),
3521 ('2020-06-01T04:05:06.111111-04:00',
3522 self.theclass(2020, 6, 1, 4, 5, 6, 111111, tzinfo=EDT)),
3523 ('2020-06-01T04:05:06.111111-0400',
3524 self.theclass(2020, 6, 1, 4, 5, 6, 111111, tzinfo=EDT)),
3525 ('2021-10-31T01:30:00.000000+01:00',
3526 self.theclass(2021, 10, 31, 1, 30, tzinfo=BST)),
3527 ('2021-10-31T01:30:00.000000+0100',
3528 self.theclass(2021, 10, 31, 1, 30, tzinfo=BST)),
3529 ('2025-01-02T03:04:05,6+000000.00',
3530 self.theclass(2025, 1, 2, 3, 4, 5, 600000, tzinfo=UTC)),
3531 ('2025-01-02T03:04:05,678+00:00:10',
3532 self.theclass(2025, 1, 2, 3, 4, 5, 678000,
3533 tzinfo=timezone(timedelta(seconds=10)))),
3534 ('2025-01-02T24:00:00', self.theclass(2025, 1, 3, 0, 0, 0)),
3535 ('2025-01-31T24:00:00', self.theclass(2025, 2, 1, 0, 0, 0)),
3536 ('2025-12-31T24:00:00', self.theclass(2026, 1, 1, 0, 0, 0))
3537 ]
3538
3539 for input_str, expected in examples:
3540 with self.subTest(input_str=input_str):
3541 actual = self.theclass.fromisoformat(input_str)
3542 self.assertEqual(actual, expected)
3543
3544 def test_fromisoformat_fails_datetime(self):
3545 # Test that fromisoformat() fails on invalid values
3546 bad_strs = [
3547 '', # Empty string
3548 '\ud800', # bpo-34454: Surrogate code point
3549 '2009.04-19T03', # Wrong first separator
3550 '2009-04.19T03', # Wrong second separator
3551 '2009-04-19T0a', # Invalid hours
3552 '2009-04-19T03:1a:45', # Invalid minutes
3553 '2009-04-19T03:15:4a', # Invalid seconds
3554 '2009-04-19T03;15:45', # Bad first time separator
3555 '2009-04-19T03:15;45', # Bad second time separator
3556 '2009-04-19T03:15:4500:00', # Bad time zone separator
3557 '2009-04-19T03:15:45.123456+24:30', # Invalid time zone offset
3558 '2009-04-19T03:15:45.123456-24:30', # Invalid negative offset
3559 '2009-04-10ᛇᛇᛇᛇᛇ12:15', # Unicode chars
3560 '2009-04\ud80010T12:15', # Surrogate char in date
3561 '2009-04-10T12\ud80015', # Surrogate char in time
3562 '2009-04-19T1', # Incomplete hours
3563 '2009-04-19T12:3', # Incomplete minutes
3564 '2009-04-19T12:30:4', # Incomplete seconds
3565 '2009-04-19T12:', # Ends with time separator
3566 '2009-04-19T12:30:', # Ends with time separator
3567 '2009-04-19T12:30:45.', # Ends with time separator
3568 '2009-04-19T12:30:45.123456+', # Ends with timezone separator
3569 '2009-04-19T12:30:45.123456-', # Ends with timezone separator
3570 '2009-04-19T12:30:45.123456-05:00a', # Extra text
3571 '2009-04-19T12:30:45.123-05:00a', # Extra text
3572 '2009-04-19T12:30:45-05:00a', # Extra text
3573 '2009-04-19T24:00:00.000001', # Has non-zero microseconds on 24:00
3574 '2009-04-19T24:00:01.000000', # Has non-zero seconds on 24:00
3575 '2009-04-19T24:01:00.000000', # Has non-zero minutes on 24:00
3576 '2009-04-32T24:00:00.000000', # Day is invalid before wrapping due to 24:00
3577 '2009-13-01T24:00:00.000000', # Month is invalid before wrapping due to 24:00
3578 '9999-12-31T24:00:00.000000', # Year is invalid after wrapping due to 24:00
3579 '2009-04-19T12:30Z12:00', # Extra time zone info after Z
3580 '2009-04-19T12:30:45:334034', # Invalid microsecond separator
3581 '2009-04-19T12:30:45.400 +02:30', # Space between ms and timezone (gh-130959)
3582 '2009-04-19T12:30:45.400 ', # Trailing space (gh-130959)
3583 '2009-04-19T12:30:45. 400', # Space before fraction (gh-130959)
3584 ]
3585
3586 for bad_str in bad_strs:
3587 with self.subTest(bad_str=bad_str):
3588 with self.assertRaises(ValueError):
3589 self.theclass.fromisoformat(bad_str)
3590
3591 def test_fromisoformat_fails_datetime_valueerror(self):
3592 pattern = re.compile(
3593 r"(year|month|day|hour|minute|second) must "
3594 r"be in \d+\.\.\d+, not \d+"
3595 )
3596 bad_strs = [
3597 "2009-04-01T12:30:90", # Second out of range
3598 "2009-04-01T12:90:45", # Minute out of range
3599 "2009-04-01T25:30:45", # Hour out of range
3600 "2009-13-01T24:00:00", # Month out of range
3601 "9999-12-31T24:00:00", # Year out of range
3602 ]
3603
3604 for bad_str in bad_strs:
3605 with self.subTest(bad_str=bad_str):
3606 with self.assertRaisesRegex(ValueError, pattern):
3607 self.theclass.fromisoformat(bad_str)
3608
3609 # days out of range have their own error message, see issue 70647
3610 with self.assertRaises(ValueError) as msg:
3611 self.theclass.fromisoformat("2009-04-32T24:00:00")
3612 self.assertIn(f"day 32 must be in range 1..30 for month 4 in year 2009", str(msg.exception))
3613
3614 def test_fromisoformat_fails_surrogate(self):
3615 # Test that when fromisoformat() fails with a surrogate character as
3616 # the separator, the error message contains the original string
3617 dtstr = "2018-01-03\ud80001:0113"
3618
3619 with self.assertRaisesRegex(ValueError, re.escape(repr(dtstr))):
3620 self.theclass.fromisoformat(dtstr)
3621
3622 def test_fromisoformat_utc(self):
3623 dt_str = '2014-04-19T13:21:13+00:00'
3624 dt = self.theclass.fromisoformat(dt_str)
3625
3626 self.assertIs(dt.tzinfo, timezone.utc)
3627
3628 def test_fromisoformat_subclass(self):
3629 class DateTimeSubclass(self.theclass):
3630 pass
3631
3632 dt = DateTimeSubclass(2014, 12, 14, 9, 30, 45, 457390,
3633 tzinfo=timezone(timedelta(hours=10, minutes=45)))
3634
3635 dt_rt = DateTimeSubclass.fromisoformat(dt.isoformat())
3636
3637 self.assertEqual(dt, dt_rt)
3638 self.assertIsInstance(dt_rt, DateTimeSubclass)
3639
3640 def test_repr_subclass(self):
3641 """Subclasses should have bare names in the repr (gh-107773)."""
3642 td = SubclassDatetime(2014, 1, 1)
3643 self.assertEqual(repr(td), "SubclassDatetime(2014, 1, 1, 0, 0)")
3644 td = SubclassDatetime(2010, 10, day=10)
3645 self.assertEqual(repr(td), "SubclassDatetime(2010, 10, 10, 0, 0)")
3646 td = SubclassDatetime(2010, 10, 2, second=3)
3647 self.assertEqual(repr(td), "SubclassDatetime(2010, 10, 2, 0, 0, 3)")
3648
3649
3650 class TestSubclassDateTime(TestDateTime):
3651 theclass = SubclassDatetime
3652 # Override tests not designed for subclass
3653 @unittest.skip('not appropriate for subclasses')
3654 def test_roundtrip(self):
3655 pass
3656
3657 class SubclassTime(time):
3658 sub_var = 1
3659
3660 class TestTime(HarmlessMixedComparison, unittest.TestCase):
3661
3662 theclass = time
3663
3664 def test_basic_attributes(self):
3665 t = self.theclass(12, 0)
3666 self.assertEqual(t.hour, 12)
3667 self.assertEqual(t.minute, 0)
3668 self.assertEqual(t.second, 0)
3669 self.assertEqual(t.microsecond, 0)
3670
3671 def test_basic_attributes_nonzero(self):
3672 # Make sure all attributes are non-zero so bugs in
3673 # bit-shifting access show up.
3674 t = self.theclass(12, 59, 59, 8000)
3675 self.assertEqual(t.hour, 12)
3676 self.assertEqual(t.minute, 59)
3677 self.assertEqual(t.second, 59)
3678 self.assertEqual(t.microsecond, 8000)
3679
3680 def test_roundtrip(self):
3681 t = self.theclass(1, 2, 3, 4)
3682
3683 # Verify t -> string -> time identity.
3684 s = repr(t)
3685 self.assertStartsWith(s, 'datetime.')
3686 s = s[9:]
3687 t2 = eval(s)
3688 self.assertEqual(t, t2)
3689
3690 # Verify identity via reconstructing from pieces.
3691 t2 = self.theclass(t.hour, t.minute, t.second,
3692 t.microsecond)
3693 self.assertEqual(t, t2)
3694
3695 def test_comparing(self):
3696 args = [1, 2, 3, 4]
3697 t1 = self.theclass(*args)
3698 t2 = self.theclass(*args)
3699 self.assertEqual(t1, t2)
3700 self.assertTrue(t1 <= t2)
3701 self.assertTrue(t1 >= t2)
3702 self.assertFalse(t1 != t2)
3703 self.assertFalse(t1 < t2)
3704 self.assertFalse(t1 > t2)
3705
3706 for i in range(len(args)):
3707 newargs = args[:]
3708 newargs[i] = args[i] + 1
3709 t2 = self.theclass(*newargs) # this is larger than t1
3710 self.assertTrue(t1 < t2)
3711 self.assertTrue(t2 > t1)
3712 self.assertTrue(t1 <= t2)
3713 self.assertTrue(t2 >= t1)
3714 self.assertTrue(t1 != t2)
3715 self.assertTrue(t2 != t1)
3716 self.assertFalse(t1 == t2)
3717 self.assertFalse(t2 == t1)
3718 self.assertFalse(t1 > t2)
3719 self.assertFalse(t2 < t1)
3720 self.assertFalse(t1 >= t2)
3721 self.assertFalse(t2 <= t1)
3722
3723 for badarg in OTHERSTUFF:
3724 self.assertEqual(t1 == badarg, False)
3725 self.assertEqual(t1 != badarg, True)
3726 self.assertEqual(badarg == t1, False)
3727 self.assertEqual(badarg != t1, True)
3728
3729 self.assertRaises(TypeError, lambda: t1 <= badarg)
3730 self.assertRaises(TypeError, lambda: t1 < badarg)
3731 self.assertRaises(TypeError, lambda: t1 > badarg)
3732 self.assertRaises(TypeError, lambda: t1 >= badarg)
3733 self.assertRaises(TypeError, lambda: badarg <= t1)
3734 self.assertRaises(TypeError, lambda: badarg < t1)
3735 self.assertRaises(TypeError, lambda: badarg > t1)
3736 self.assertRaises(TypeError, lambda: badarg >= t1)
3737
3738 def test_bad_constructor_arguments(self):
3739 # bad hours
3740 self.theclass(0, 0) # no exception
3741 self.theclass(23, 0) # no exception
3742 self.assertRaises(ValueError, self.theclass, -1, 0)
3743 self.assertRaises(ValueError, self.theclass, 24, 0)
3744 # bad minutes
3745 self.theclass(23, 0) # no exception
3746 self.theclass(23, 59) # no exception
3747 self.assertRaises(ValueError, self.theclass, 23, -1)
3748 self.assertRaises(ValueError, self.theclass, 23, 60)
3749 # bad seconds
3750 self.theclass(23, 59, 0) # no exception
3751 self.theclass(23, 59, 59) # no exception
3752 self.assertRaises(ValueError, self.theclass, 23, 59, -1)
3753 self.assertRaises(ValueError, self.theclass, 23, 59, 60)
3754 # bad microseconds
3755 self.theclass(23, 59, 59, 0) # no exception
3756 self.theclass(23, 59, 59, 999999) # no exception
3757 self.assertRaises(ValueError, self.theclass, 23, 59, 59, -1)
3758 self.assertRaises(ValueError, self.theclass, 23, 59, 59, 1000000)
3759
3760 def test_hash_equality(self):
3761 d = self.theclass(23, 30, 17)
3762 e = self.theclass(23, 30, 17)
3763 self.assertEqual(d, e)
3764 self.assertEqual(hash(d), hash(e))
3765
3766 dic = {d: 1}
3767 dic[e] = 2
3768 self.assertEqual(len(dic), 1)
3769 self.assertEqual(dic[d], 2)
3770 self.assertEqual(dic[e], 2)
3771
3772 d = self.theclass(0, 5, 17)
3773 e = self.theclass(0, 5, 17)
3774 self.assertEqual(d, e)
3775 self.assertEqual(hash(d), hash(e))
3776
3777 dic = {d: 1}
3778 dic[e] = 2
3779 self.assertEqual(len(dic), 1)
3780 self.assertEqual(dic[d], 2)
3781 self.assertEqual(dic[e], 2)
3782
3783 def test_isoformat(self):
3784 t = self.theclass(4, 5, 1, 123)
3785 self.assertEqual(t.isoformat(), "04:05:01.000123")
3786 self.assertEqual(t.isoformat(), str(t))
3787
3788 t = self.theclass()
3789 self.assertEqual(t.isoformat(), "00:00:00")
3790 self.assertEqual(t.isoformat(), str(t))
3791
3792 t = self.theclass(microsecond=1)
3793 self.assertEqual(t.isoformat(), "00:00:00.000001")
3794 self.assertEqual(t.isoformat(), str(t))
3795
3796 t = self.theclass(microsecond=10)
3797 self.assertEqual(t.isoformat(), "00:00:00.000010")
3798 self.assertEqual(t.isoformat(), str(t))
3799
3800 t = self.theclass(microsecond=100)
3801 self.assertEqual(t.isoformat(), "00:00:00.000100")
3802 self.assertEqual(t.isoformat(), str(t))
3803
3804 t = self.theclass(microsecond=1000)
3805 self.assertEqual(t.isoformat(), "00:00:00.001000")
3806 self.assertEqual(t.isoformat(), str(t))
3807
3808 t = self.theclass(microsecond=10000)
3809 self.assertEqual(t.isoformat(), "00:00:00.010000")
3810 self.assertEqual(t.isoformat(), str(t))
3811
3812 t = self.theclass(microsecond=100000)
3813 self.assertEqual(t.isoformat(), "00:00:00.100000")
3814 self.assertEqual(t.isoformat(), str(t))
3815
3816 t = self.theclass(hour=12, minute=34, second=56, microsecond=123456)
3817 self.assertEqual(t.isoformat(timespec='hours'), "12")
3818 self.assertEqual(t.isoformat(timespec='minutes'), "12:34")
3819 self.assertEqual(t.isoformat(timespec='seconds'), "12:34:56")
3820 self.assertEqual(t.isoformat(timespec='milliseconds'), "12:34:56.123")
3821 self.assertEqual(t.isoformat(timespec='microseconds'), "12:34:56.123456")
3822 self.assertEqual(t.isoformat(timespec='auto'), "12:34:56.123456")
3823 self.assertRaises(ValueError, t.isoformat, timespec='monkey')
3824 # bpo-34482: Check that surrogates are handled properly.
3825 self.assertRaises(ValueError, t.isoformat, timespec='\ud800')
3826
3827 t = self.theclass(hour=12, minute=34, second=56, microsecond=999500)
3828 self.assertEqual(t.isoformat(timespec='milliseconds'), "12:34:56.999")
3829
3830 t = self.theclass(hour=12, minute=34, second=56, microsecond=0)
3831 self.assertEqual(t.isoformat(timespec='milliseconds'), "12:34:56.000")
3832 self.assertEqual(t.isoformat(timespec='microseconds'), "12:34:56.000000")
3833 self.assertEqual(t.isoformat(timespec='auto'), "12:34:56")
3834
3835 def test_isoformat_timezone(self):
3836 tzoffsets = [
3837 ('05:00', timedelta(hours=5)),
3838 ('02:00', timedelta(hours=2)),
3839 ('06:27', timedelta(hours=6, minutes=27)),
3840 ('12:32:30', timedelta(hours=12, minutes=32, seconds=30)),
3841 ('02:04:09.123456', timedelta(hours=2, minutes=4, seconds=9, microseconds=123456))
3842 ]
3843
3844 tzinfos = [
3845 ('', None),
3846 ('+00:00', timezone.utc),
3847 ('+00:00', timezone(timedelta(0))),
3848 ]
3849
3850 tzinfos += [
3851 (prefix + expected, timezone(sign * td))
3852 for expected, td in tzoffsets
3853 for prefix, sign in [('-', -1), ('+', 1)]
3854 ]
3855
3856 t_base = self.theclass(12, 37, 9)
3857 exp_base = '12:37:09'
3858
3859 for exp_tz, tzi in tzinfos:
3860 t = t_base.replace(tzinfo=tzi)
3861 exp = exp_base + exp_tz
3862 with self.subTest(tzi=tzi):
3863 assert t.isoformat() == exp
3864
3865 def test_1653736(self):
3866 # verify it doesn't accept extra keyword arguments
3867 t = self.theclass(second=1)
3868 self.assertRaises(TypeError, t.isoformat, foo=3)
3869
3870 def test_strftime(self):
3871 t = self.theclass(1, 2, 3, 4)
3872 self.assertEqual(t.strftime('%H %M %S %f'), "01 02 03 000004")
3873 # A naive object replaces %z, %:z and %Z with empty strings.
3874 self.assertEqual(t.strftime("'%z' '%:z' '%Z'"), "'' '' ''")
3875
3876 # bpo-34482: Check that surrogates don't cause a crash.
3877 try:
3878 t.strftime('%H\ud800%M')
3879 except UnicodeEncodeError:
3880 pass
3881
3882 # gh-85432: The parameter was named "fmt" in the pure-Python impl.
3883 t.strftime(format="%f")
3884
3885 def test_strftime_special(self):
3886 t = self.theclass(1, 2, 3, 4)
3887 s1 = t.strftime('%I%p%Z')
3888 s2 = t.strftime('%X')
3889 # gh-52551, gh-78662: Unicode strings should pass through strftime,
3890 # independently from locale.
3891 self.assertEqual(t.strftime('\U0001f40d'), '\U0001f40d')
3892 self.assertEqual(t.strftime('\U0001f4bb%I%p%Z\U0001f40d%X'), f'\U0001f4bb{s1}\U0001f40d{s2}')
3893 self.assertEqual(t.strftime('%I%p%Z\U0001f4bb%X\U0001f40d'), f'{s1}\U0001f4bb{s2}\U0001f40d')
3894 # Lone surrogates should pass through.
3895 self.assertEqual(t.strftime('\ud83d'), '\ud83d')
3896 self.assertEqual(t.strftime('\udc0d'), '\udc0d')
3897 self.assertEqual(t.strftime('\ud83d%I%p%Z\udc0d%X'), f'\ud83d{s1}\udc0d{s2}')
3898 self.assertEqual(t.strftime('%I%p%Z\ud83d%X\udc0d'), f'{s1}\ud83d{s2}\udc0d')
3899 self.assertEqual(t.strftime('%I%p%Z\udc0d%X\ud83d'), f'{s1}\udc0d{s2}\ud83d')
3900 # Surrogate pairs should not recombine.
3901 self.assertEqual(t.strftime('\ud83d\udc0d'), '\ud83d\udc0d')
3902 self.assertEqual(t.strftime('%I%p%Z\ud83d\udc0d%X'), f'{s1}\ud83d\udc0d{s2}')
3903 # Surrogate-escaped bytes should not recombine.
3904 self.assertEqual(t.strftime('\udcf0\udc9f\udc90\udc8d'), '\udcf0\udc9f\udc90\udc8d')
3905 self.assertEqual(t.strftime('%I%p%Z\udcf0\udc9f\udc90\udc8d%X'), f'{s1}\udcf0\udc9f\udc90\udc8d{s2}')
3906 # gh-124531: The null character should not terminate the format string.
3907 self.assertEqual(t.strftime('\0'), '\0')
3908 self.assertEqual(t.strftime('\0'*1000), '\0'*1000)
3909 self.assertEqual(t.strftime('\0%I%p%Z\0%X'), f'\0{s1}\0{s2}')
3910 self.assertEqual(t.strftime('%I%p%Z\0%X\0'), f'{s1}\0{s2}\0')
3911
3912 def test_format(self):
3913 t = self.theclass(1, 2, 3, 4)
3914 self.assertEqual(t.__format__(''), str(t))
3915
3916 with self.assertRaisesRegex(TypeError, 'must be str, not int'):
3917 t.__format__(123)
3918
3919 # check that a derived class's __str__() gets called
3920 class A(self.theclass):
3921 def __str__(self):
3922 return 'A'
3923 a = A(1, 2, 3, 4)
3924 self.assertEqual(a.__format__(''), 'A')
3925
3926 # check that a derived class's strftime gets called
3927 class B(self.theclass):
3928 def strftime(self, format_spec):
3929 return 'B'
3930 b = B(1, 2, 3, 4)
3931 self.assertEqual(b.__format__(''), str(t))
3932
3933 for fmt in ['%H %M %S',
3934 ]:
3935 self.assertEqual(t.__format__(fmt), t.strftime(fmt))
3936 self.assertEqual(a.__format__(fmt), t.strftime(fmt))
3937 self.assertEqual(b.__format__(fmt), 'B')
3938
3939 def test_str(self):
3940 self.assertEqual(str(self.theclass(1, 2, 3, 4)), "01:02:03.000004")
3941 self.assertEqual(str(self.theclass(10, 2, 3, 4000)), "10:02:03.004000")
3942 self.assertEqual(str(self.theclass(0, 2, 3, 400000)), "00:02:03.400000")
3943 self.assertEqual(str(self.theclass(12, 2, 3, 0)), "12:02:03")
3944 self.assertEqual(str(self.theclass(23, 15, 0, 0)), "23:15:00")
3945
3946 def test_repr(self):
3947 name = 'datetime.' + self.theclass.__name__
3948 self.assertEqual(repr(self.theclass(1, 2, 3, 4)),
3949 "%s(1, 2, 3, 4)" % name)
3950 self.assertEqual(repr(self.theclass(10, 2, 3, 4000)),
3951 "%s(10, 2, 3, 4000)" % name)
3952 self.assertEqual(repr(self.theclass(0, 2, 3, 400000)),
3953 "%s(0, 2, 3, 400000)" % name)
3954 self.assertEqual(repr(self.theclass(12, 2, 3, 0)),
3955 "%s(12, 2, 3)" % name)
3956 self.assertEqual(repr(self.theclass(23, 15, 0, 0)),
3957 "%s(23, 15)" % name)
3958
3959 def test_repr_subclass(self):
3960 """Subclasses should have bare names in the repr (gh-107773)."""
3961 td = SubclassTime(hour=1)
3962 self.assertEqual(repr(td), "SubclassTime(1, 0)")
3963 td = SubclassTime(hour=2, minute=30)
3964 self.assertEqual(repr(td), "SubclassTime(2, 30)")
3965 td = SubclassTime(hour=2, minute=30, second=11)
3966 self.assertEqual(repr(td), "SubclassTime(2, 30, 11)")
3967 td = SubclassTime(minute=30, second=11, fold=0)
3968 self.assertEqual(repr(td), "SubclassTime(0, 30, 11)")
3969 td = SubclassTime(minute=30, second=11, fold=1)
3970 self.assertEqual(repr(td), "SubclassTime(0, 30, 11, fold=1)")
3971
3972 def test_resolution_info(self):
3973 self.assertIsInstance(self.theclass.min, self.theclass)
3974 self.assertIsInstance(self.theclass.max, self.theclass)
3975 self.assertIsInstance(self.theclass.resolution, timedelta)
3976 self.assertTrue(self.theclass.max > self.theclass.min)
3977
3978 def test_pickling(self):
3979 args = 20, 59, 16, 64**2
3980 orig = self.theclass(*args)
3981 for pickler, unpickler, proto in pickle_choices:
3982 green = pickler.dumps(orig, proto)
3983 derived = unpickler.loads(green)
3984 self.assertEqual(orig, derived)
3985 self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2))
3986
3987 def test_pickling_subclass_time(self):
3988 args = 20, 59, 16, 64**2
3989 orig = SubclassTime(*args)
3990 for pickler, unpickler, proto in pickle_choices:
3991 green = pickler.dumps(orig, proto)
3992 derived = unpickler.loads(green)
3993 self.assertEqual(orig, derived)
3994 self.assertTrue(isinstance(derived, SubclassTime))
3995
3996 def test_compat_unpickle(self):
3997 tests = [
3998 (b"cdatetime\ntime\n(S'\\x14;\\x10\\x00\\x10\\x00'\ntR.",
3999 (20, 59, 16, 64**2)),
4000 (b'cdatetime\ntime\n(U\x06\x14;\x10\x00\x10\x00tR.',
4001 (20, 59, 16, 64**2)),
4002 (b'\x80\x02cdatetime\ntime\nU\x06\x14;\x10\x00\x10\x00\x85R.',
4003 (20, 59, 16, 64**2)),
4004 (b"cdatetime\ntime\n(S'\\x14;\\x19\\x00\\x10\\x00'\ntR.",
4005 (20, 59, 25, 64**2)),
4006 (b'cdatetime\ntime\n(U\x06\x14;\x19\x00\x10\x00tR.',
4007 (20, 59, 25, 64**2)),
4008 (b'\x80\x02cdatetime\ntime\nU\x06\x14;\x19\x00\x10\x00\x85R.',
4009 (20, 59, 25, 64**2)),
4010 ]
4011 for i, (data, args) in enumerate(tests):
4012 with self.subTest(i=i):
4013 expected = self.theclass(*args)
4014 for loads in pickle_loads:
4015 derived = loads(data, encoding='latin1')
4016 self.assertEqual(derived, expected)
4017
4018 def test_strptime(self):
4019 # bpo-34482: Check that surrogates are handled properly.
4020 inputs = [
4021 (self.theclass(13, 2, 47, 197000), '13:02:47.197', '%H:%M:%S.%f'),
4022 (self.theclass(13, 2, 47, 197000), '13:02\ud80047.197', '%H:%M\ud800%S.%f'),
4023 (self.theclass(13, 2, 47, 197000), '13\ud80002:47.197', '%H\ud800%M:%S.%f'),
4024 ]
4025 for expected, string, format in inputs:
4026 with self.subTest(string=string, format=format):
4027 got = self.theclass.strptime(string, format)
4028 self.assertEqual(expected, got)
4029 self.assertIs(type(got), self.theclass)
4030
4031 def test_strptime_tz(self):
4032 strptime = self.theclass.strptime
4033 self.assertEqual(strptime("+0002", "%z").utcoffset(), 2 * MINUTE)
4034 self.assertEqual(strptime("-0002", "%z").utcoffset(), -2 * MINUTE)
4035 self.assertEqual(
4036 strptime("-00:02:01.000003", "%z").utcoffset(),
4037 -timedelta(minutes=2, seconds=1, microseconds=3)
4038 )
4039 # Only local timezone and UTC are supported
4040 for tzseconds, tzname in ((0, 'UTC'), (0, 'GMT'),
4041 (-_time.timezone, _time.tzname[0])):
4042 if tzseconds < 0:
4043 sign = '-'
4044 seconds = -tzseconds
4045 else:
4046 sign ='+'
4047 seconds = tzseconds
4048 hours, minutes = divmod(seconds//60, 60)
4049 tstr = "{}{:02d}{:02d} {}".format(sign, hours, minutes, tzname)
4050 with self.subTest(tstr=tstr):
4051 t = strptime(tstr, "%z %Z")
4052 self.assertEqual(t.utcoffset(), timedelta(seconds=tzseconds))
4053 self.assertEqual(t.tzname(), tzname)
4054 self.assertIs(type(t), self.theclass)
4055
4056 # Can produce inconsistent time
4057 tstr, fmt = "+1234 UTC", "%z %Z"
4058 t = strptime(tstr, fmt)
4059 self.assertEqual(t.utcoffset(), 12 * HOUR + 34 * MINUTE)
4060 self.assertEqual(t.tzname(), 'UTC')
4061 # yet will roundtrip
4062 self.assertEqual(t.strftime(fmt), tstr)
4063
4064 # Produce naive time if no %z is provided
4065 self.assertEqual(strptime("UTC", "%Z").tzinfo, None)
4066
4067 def test_strptime_errors(self):
4068 for tzstr in ("-2400", "-000", "z"):
4069 with self.assertRaises(ValueError):
4070 self.theclass.strptime(tzstr, "%z")
4071
4072 def test_strptime_single_digit(self):
4073 # bpo-34903: Check that single digit times are allowed.
4074 t = self.theclass(4, 5, 6)
4075 inputs = [
4076 ('%H', '4:05:06', '%H:%M:%S', t),
4077 ('%M', '04:5:06', '%H:%M:%S', t),
4078 ('%S', '04:05:6', '%H:%M:%S', t),
4079 ('%I', '4am:05:06', '%I%p:%M:%S', t),
4080 ]
4081 for reason, string, format, target in inputs:
4082 reason = 'test single digit ' + reason
4083 with self.subTest(reason=reason,
4084 string=string,
4085 format=format,
4086 target=target):
4087 newdate = self.theclass.strptime(string, format)
4088 self.assertEqual(newdate, target, msg=reason)
4089
4090 def test_bool(self):
4091 # time is always True.
4092 cls = self.theclass
4093 self.assertTrue(cls(1))
4094 self.assertTrue(cls(0, 1))
4095 self.assertTrue(cls(0, 0, 1))
4096 self.assertTrue(cls(0, 0, 0, 1))
4097 self.assertTrue(cls(0))
4098 self.assertTrue(cls())
4099
4100 def test_replace(self):
4101 cls = self.theclass
4102 args = [1, 2, 3, 4]
4103 base = cls(*args)
4104 self.assertEqual(base.replace(), base)
4105 self.assertEqual(copy.replace(base), base)
4106
4107 changes = (("hour", 5),
4108 ("minute", 6),
4109 ("second", 7),
4110 ("microsecond", 8))
4111 for i, (name, newval) in enumerate(changes):
4112 newargs = args[:]
4113 newargs[i] = newval
4114 expected = cls(*newargs)
4115 self.assertEqual(base.replace(**{name: newval}), expected)
4116 self.assertEqual(copy.replace(base, **{name: newval}), expected)
4117
4118 # Out of bounds.
4119 base = cls(1)
4120 self.assertRaises(ValueError, base.replace, hour=24)
4121 self.assertRaises(ValueError, base.replace, minute=-1)
4122 self.assertRaises(ValueError, base.replace, second=100)
4123 self.assertRaises(ValueError, base.replace, microsecond=1000000)
4124 self.assertRaises(ValueError, copy.replace, base, hour=24)
4125 self.assertRaises(ValueError, copy.replace, base, minute=-1)
4126 self.assertRaises(ValueError, copy.replace, base, second=100)
4127 self.assertRaises(ValueError, copy.replace, base, microsecond=1000000)
4128
4129 def test_subclass_replace(self):
4130 class TimeSubclass(self.theclass):
4131 def __new__(cls, *args, **kwargs):
4132 result = self.theclass.__new__(cls, *args, **kwargs)
4133 result.extra = 7
4134 return result
4135
4136 ctime = TimeSubclass(12, 30)
4137 ctime2 = TimeSubclass(12, 30, fold=1)
4138
4139 test_cases = [
4140 ('self.replace', ctime.replace(hour=10), 0),
4141 ('self.replace', ctime2.replace(hour=10), 1),
4142 ('copy.replace', copy.replace(ctime, hour=10), 0),
4143 ('copy.replace', copy.replace(ctime2, hour=10), 1),
4144 ]
4145
4146 for name, res, fold in test_cases:
4147 with self.subTest(name, fold=fold):
4148 self.assertIs(type(res), TimeSubclass)
4149 self.assertEqual(res.hour, 10)
4150 self.assertEqual(res.minute, 30)
4151 self.assertEqual(res.extra, 7)
4152 self.assertEqual(res.fold, fold)
4153
4154 def test_subclass_time(self):
4155
4156 class C(self.theclass):
4157 theAnswer = 42
4158
4159 def __new__(cls, *args, **kws):
4160 temp = kws.copy()
4161 extra = temp.pop('extra')
4162 result = self.theclass.__new__(cls, *args, **temp)
4163 result.extra = extra
4164 return result
4165
4166 def newmeth(self, start):
4167 return start + self.hour + self.second
4168
4169 args = 4, 5, 6
4170
4171 dt1 = self.theclass(*args)
4172 dt2 = C(*args, **{'extra': 7})
4173
4174 self.assertEqual(dt2.__class__, C)
4175 self.assertEqual(dt2.theAnswer, 42)
4176 self.assertEqual(dt2.extra, 7)
4177 self.assertEqual(dt1.isoformat(), dt2.isoformat())
4178 self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.second - 7)
4179
4180 def test_backdoor_resistance(self):
4181 # see TestDate.test_backdoor_resistance().
4182 base = '2:59.0'
4183 for hour_byte in ' ', '9', chr(24), '\xff':
4184 self.assertRaises(TypeError, self.theclass,
4185 hour_byte + base[1:])
4186 # Good bytes, but bad tzinfo:
4187 with self.assertRaisesRegex(TypeError, '^bad tzinfo state arg$'):
4188 self.theclass(bytes([1] * len(base)), 'EST')
4189
4190 # A mixin for classes with a tzinfo= argument. Subclasses must define
4191 # theclass as a class attribute, and theclass(1, 1, 1, tzinfo=whatever)
4192 # must be legit (which is true for time and datetime).
4193 class TZInfoBase:
4194
4195 def test_argument_passing(self):
4196 cls = self.theclass
4197 # A datetime passes itself on, a time passes None.
4198 class introspective(tzinfo):
4199 def tzname(self, dt): return dt and "real" or "none"
4200 def utcoffset(self, dt):
4201 return timedelta(minutes = dt and 42 or -42)
4202 dst = utcoffset
4203
4204 obj = cls(1, 2, 3, tzinfo=introspective())
4205
4206 expected = cls is time and "none" or "real"
4207 self.assertEqual(obj.tzname(), expected)
4208
4209 expected = timedelta(minutes=(cls is time and -42 or 42))
4210 self.assertEqual(obj.utcoffset(), expected)
4211 self.assertEqual(obj.dst(), expected)
4212
4213 def test_bad_tzinfo_classes(self):
4214 cls = self.theclass
4215 self.assertRaises(TypeError, cls, 1, 1, 1, tzinfo=12)
4216
4217 class NiceTry(object):
4218 def __init__(self): pass
4219 def utcoffset(self, dt): pass
4220 self.assertRaises(TypeError, cls, 1, 1, 1, tzinfo=NiceTry)
4221
4222 class BetterTry(tzinfo):
4223 def __init__(self): pass
4224 def utcoffset(self, dt): pass
4225 b = BetterTry()
4226 t = cls(1, 1, 1, tzinfo=b)
4227 self.assertIs(t.tzinfo, b)
4228
4229 def test_utc_offset_out_of_bounds(self):
4230 class Edgy(tzinfo):
4231 def __init__(self, offset):
4232 self.offset = timedelta(minutes=offset)
4233 def utcoffset(self, dt):
4234 return self.offset
4235
4236 cls = self.theclass
4237 for offset, legit in ((-1440, False),
4238 (-1439, True),
4239 (1439, True),
4240 (1440, False)):
4241 if cls is time:
4242 t = cls(1, 2, 3, tzinfo=Edgy(offset))
4243 elif cls is datetime:
4244 t = cls(6, 6, 6, 1, 2, 3, tzinfo=Edgy(offset))
4245 else:
4246 assert 0, "impossible"
4247 if legit:
4248 aofs = abs(offset)
4249 h, m = divmod(aofs, 60)
4250 tag = "%c%02d:%02d" % (offset < 0 and '-' or '+', h, m)
4251 if isinstance(t, datetime):
4252 t = t.timetz()
4253 self.assertEqual(str(t), "01:02:03" + tag)
4254 else:
4255 self.assertRaises(ValueError, str, t)
4256
4257 def test_tzinfo_classes(self):
4258 cls = self.theclass
4259 class C1(tzinfo):
4260 def utcoffset(self, dt): return None
4261 def dst(self, dt): return None
4262 def tzname(self, dt): return None
4263 for t in (cls(1, 1, 1),
4264 cls(1, 1, 1, tzinfo=None),
4265 cls(1, 1, 1, tzinfo=C1())):
4266 self.assertIsNone(t.utcoffset())
4267 self.assertIsNone(t.dst())
4268 self.assertIsNone(t.tzname())
4269
4270 class C3(tzinfo):
4271 def utcoffset(self, dt): return timedelta(minutes=-1439)
4272 def dst(self, dt): return timedelta(minutes=1439)
4273 def tzname(self, dt): return "aname"
4274 t = cls(1, 1, 1, tzinfo=C3())
4275 self.assertEqual(t.utcoffset(), timedelta(minutes=-1439))
4276 self.assertEqual(t.dst(), timedelta(minutes=1439))
4277 self.assertEqual(t.tzname(), "aname")
4278
4279 # Wrong types.
4280 class C4(tzinfo):
4281 def utcoffset(self, dt): return "aname"
4282 def dst(self, dt): return 7
4283 def tzname(self, dt): return 0
4284 t = cls(1, 1, 1, tzinfo=C4())
4285 self.assertRaises(TypeError, t.utcoffset)
4286 self.assertRaises(TypeError, t.dst)
4287 self.assertRaises(TypeError, t.tzname)
4288
4289 # Offset out of range.
4290 class C6(tzinfo):
4291 def utcoffset(self, dt): return timedelta(hours=-24)
4292 def dst(self, dt): return timedelta(hours=24)
4293 t = cls(1, 1, 1, tzinfo=C6())
4294 self.assertRaises(ValueError, t.utcoffset)
4295 self.assertRaises(ValueError, t.dst)
4296
4297 # Not a whole number of seconds.
4298 class C7(tzinfo):
4299 def utcoffset(self, dt): return timedelta(microseconds=61)
4300 def dst(self, dt): return timedelta(microseconds=-81)
4301 t = cls(1, 1, 1, tzinfo=C7())
4302 self.assertEqual(t.utcoffset(), timedelta(microseconds=61))
4303 self.assertEqual(t.dst(), timedelta(microseconds=-81))
4304
4305 def test_aware_compare(self):
4306 cls = self.theclass
4307
4308 # Ensure that utcoffset() gets ignored if the comparands have
4309 # the same tzinfo member.
4310 class OperandDependentOffset(tzinfo):
4311 def utcoffset(self, t):
4312 if t.minute < 10:
4313 # d0 and d1 equal after adjustment
4314 return timedelta(minutes=t.minute)
4315 else:
4316 # d2 off in the weeds
4317 return timedelta(minutes=59)
4318
4319 base = cls(8, 9, 10, tzinfo=OperandDependentOffset())
4320 d0 = base.replace(minute=3)
4321 d1 = base.replace(minute=9)
4322 d2 = base.replace(minute=11)
4323 for x in d0, d1, d2:
4324 for y in d0, d1, d2:
4325 for op in lt, le, gt, ge, eq, ne:
4326 got = op(x, y)
4327 expected = op(x.minute, y.minute)
4328 self.assertEqual(got, expected)
4329
4330 # However, if they're different members, uctoffset is not ignored.
4331 # Note that a time can't actually have an operand-dependent offset,
4332 # though (and time.utcoffset() passes None to tzinfo.utcoffset()),
4333 # so skip this test for time.
4334 if cls is not time:
4335 d0 = base.replace(minute=3, tzinfo=OperandDependentOffset())
4336 d1 = base.replace(minute=9, tzinfo=OperandDependentOffset())
4337 d2 = base.replace(minute=11, tzinfo=OperandDependentOffset())
4338 for x in d0, d1, d2:
4339 for y in d0, d1, d2:
4340 got = (x > y) - (x < y)
4341 if (x is d0 or x is d1) and (y is d0 or y is d1):
4342 expected = 0
4343 elif x is y is d2:
4344 expected = 0
4345 elif x is d2:
4346 expected = -1
4347 else:
4348 assert y is d2
4349 expected = 1
4350 self.assertEqual(got, expected)
4351
4352
4353 # Testing time objects with a non-None tzinfo.
4354 class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase):
4355 theclass = time
4356
4357 def test_empty(self):
4358 t = self.theclass()
4359 self.assertEqual(t.hour, 0)
4360 self.assertEqual(t.minute, 0)
4361 self.assertEqual(t.second, 0)
4362 self.assertEqual(t.microsecond, 0)
4363 self.assertIsNone(t.tzinfo)
4364
4365 def test_zones(self):
4366 est = FixedOffset(-300, "EST", 1)
4367 utc = FixedOffset(0, "UTC", -2)
4368 met = FixedOffset(60, "MET", 3)
4369 t1 = time( 7, 47, tzinfo=est)
4370 t2 = time(12, 47, tzinfo=utc)
4371 t3 = time(13, 47, tzinfo=met)
4372 t4 = time(microsecond=40)
4373 t5 = time(microsecond=40, tzinfo=utc)
4374
4375 self.assertEqual(t1.tzinfo, est)
4376 self.assertEqual(t2.tzinfo, utc)
4377 self.assertEqual(t3.tzinfo, met)
4378 self.assertIsNone(t4.tzinfo)
4379 self.assertEqual(t5.tzinfo, utc)
4380
4381 self.assertEqual(t1.utcoffset(), timedelta(minutes=-300))
4382 self.assertEqual(t2.utcoffset(), timedelta(minutes=0))
4383 self.assertEqual(t3.utcoffset(), timedelta(minutes=60))
4384 self.assertIsNone(t4.utcoffset())
4385 self.assertRaises(TypeError, t1.utcoffset, "no args")
4386
4387 self.assertEqual(t1.tzname(), "EST")
4388 self.assertEqual(t2.tzname(), "UTC")
4389 self.assertEqual(t3.tzname(), "MET")
4390 self.assertIsNone(t4.tzname())
4391 self.assertRaises(TypeError, t1.tzname, "no args")
4392
4393 self.assertEqual(t1.dst(), timedelta(minutes=1))
4394 self.assertEqual(t2.dst(), timedelta(minutes=-2))
4395 self.assertEqual(t3.dst(), timedelta(minutes=3))
4396 self.assertIsNone(t4.dst())
4397 self.assertRaises(TypeError, t1.dst, "no args")
4398
4399 self.assertEqual(hash(t1), hash(t2))
4400 self.assertEqual(hash(t1), hash(t3))
4401 self.assertEqual(hash(t2), hash(t3))
4402
4403 self.assertEqual(t1, t2)
4404 self.assertEqual(t1, t3)
4405 self.assertEqual(t2, t3)
4406 self.assertNotEqual(t4, t5) # mixed tz-aware & naive
4407 self.assertRaises(TypeError, lambda: t4 < t5) # mixed tz-aware & naive
4408 self.assertRaises(TypeError, lambda: t5 < t4) # mixed tz-aware & naive
4409
4410 self.assertEqual(str(t1), "07:47:00-05:00")
4411 self.assertEqual(str(t2), "12:47:00+00:00")
4412 self.assertEqual(str(t3), "13:47:00+01:00")
4413 self.assertEqual(str(t4), "00:00:00.000040")
4414 self.assertEqual(str(t5), "00:00:00.000040+00:00")
4415
4416 self.assertEqual(t1.isoformat(), "07:47:00-05:00")
4417 self.assertEqual(t2.isoformat(), "12:47:00+00:00")
4418 self.assertEqual(t3.isoformat(), "13:47:00+01:00")
4419 self.assertEqual(t4.isoformat(), "00:00:00.000040")
4420 self.assertEqual(t5.isoformat(), "00:00:00.000040+00:00")
4421
4422 d = 'datetime.time'
4423 self.assertEqual(repr(t1), d + "(7, 47, tzinfo=est)")
4424 self.assertEqual(repr(t2), d + "(12, 47, tzinfo=utc)")
4425 self.assertEqual(repr(t3), d + "(13, 47, tzinfo=met)")
4426 self.assertEqual(repr(t4), d + "(0, 0, 0, 40)")
4427 self.assertEqual(repr(t5), d + "(0, 0, 0, 40, tzinfo=utc)")
4428
4429 self.assertEqual(t1.strftime("%H:%M:%S %%Z=%Z %%z=%z %%:z=%:z"),
4430 "07:47:00 %Z=EST %z=-0500 %:z=-05:00")
4431 self.assertEqual(t2.strftime("%H:%M:%S %Z %z %:z"), "12:47:00 UTC +0000 +00:00")
4432 self.assertEqual(t3.strftime("%H:%M:%S %Z %z %:z"), "13:47:00 MET +0100 +01:00")
4433
4434 yuck = FixedOffset(-1439, "%z %Z %%z%%Z")
4435 t1 = time(23, 59, tzinfo=yuck)
4436 self.assertEqual(t1.strftime("%H:%M %%Z='%Z' %%z='%z'"),
4437 "23:59 %Z='%z %Z %%z%%Z' %z='-2359'")
4438
4439 # Check that an invalid tzname result raises an exception.
4440 class Badtzname(tzinfo):
4441 tz = 42
4442 def tzname(self, dt): return self.tz
4443 t = time(2, 3, 4, tzinfo=Badtzname())
4444 self.assertEqual(t.strftime("%H:%M:%S"), "02:03:04")
4445 self.assertRaises(TypeError, t.strftime, "%Z")
4446
4447 # Issue #6697:
4448 Badtzname.tz = '\ud800'
4449 self.assertEqual(t.strftime("%Z"), '\ud800')
4450
4451 def test_hash_edge_cases(self):
4452 # Offsets that overflow a basic time.
4453 t1 = self.theclass(0, 1, 2, 3, tzinfo=FixedOffset(1439, ""))
4454 t2 = self.theclass(0, 0, 2, 3, tzinfo=FixedOffset(1438, ""))
4455 self.assertEqual(hash(t1), hash(t2))
4456
4457 t1 = self.theclass(23, 58, 6, 100, tzinfo=FixedOffset(-1000, ""))
4458 t2 = self.theclass(23, 48, 6, 100, tzinfo=FixedOffset(-1010, ""))
4459 self.assertEqual(hash(t1), hash(t2))
4460
4461 def test_pickling(self):
4462 # Try one without a tzinfo.
4463 args = 20, 59, 16, 64**2
4464 orig = self.theclass(*args)
4465 for pickler, unpickler, proto in pickle_choices:
4466 green = pickler.dumps(orig, proto)
4467 derived = unpickler.loads(green)
4468 self.assertEqual(orig, derived)
4469 self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2))
4470
4471 # Try one with a tzinfo.
4472 tinfo = PicklableFixedOffset(-300, 'cookie')
4473 orig = self.theclass(5, 6, 7, tzinfo=tinfo)
4474 for pickler, unpickler, proto in pickle_choices:
4475 green = pickler.dumps(orig, proto)
4476 derived = unpickler.loads(green)
4477 self.assertEqual(orig, derived)
4478 self.assertIsInstance(derived.tzinfo, PicklableFixedOffset)
4479 self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
4480 self.assertEqual(derived.tzname(), 'cookie')
4481 self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2))
4482
4483 def test_compat_unpickle(self):
4484 tests = [
4485 b"cdatetime\ntime\n(S'\\x05\\x06\\x07\\x01\\xe2@'\n"
4486 b"ctest.datetimetester\nPicklableFixedOffset\n(tR"
4487 b"(dS'_FixedOffset__offset'\ncdatetime\ntimedelta\n"
4488 b"(I-1\nI68400\nI0\ntRs"
4489 b"S'_FixedOffset__dstoffset'\nNs"
4490 b"S'_FixedOffset__name'\nS'cookie'\nsbtR.",
4491
4492 b'cdatetime\ntime\n(U\x06\x05\x06\x07\x01\xe2@'
4493 b'ctest.datetimetester\nPicklableFixedOffset\n)R'
4494 b'}(U\x14_FixedOffset__offsetcdatetime\ntimedelta\n'
4495 b'(J\xff\xff\xff\xffJ0\x0b\x01\x00K\x00tR'
4496 b'U\x17_FixedOffset__dstoffsetN'
4497 b'U\x12_FixedOffset__nameU\x06cookieubtR.',
4498
4499 b'\x80\x02cdatetime\ntime\nU\x06\x05\x06\x07\x01\xe2@'
4500 b'ctest.datetimetester\nPicklableFixedOffset\n)R'
4501 b'}(U\x14_FixedOffset__offsetcdatetime\ntimedelta\n'
4502 b'J\xff\xff\xff\xffJ0\x0b\x01\x00K\x00\x87R'
4503 b'U\x17_FixedOffset__dstoffsetN'
4504 b'U\x12_FixedOffset__nameU\x06cookieub\x86R.',
4505 ]
4506
4507 tinfo = PicklableFixedOffset(-300, 'cookie')
4508 expected = self.theclass(5, 6, 7, 123456, tzinfo=tinfo)
4509 for data in tests:
4510 for loads in pickle_loads:
4511 derived = loads(data, encoding='latin1')
4512 self.assertEqual(derived, expected, repr(data))
4513 self.assertIsInstance(derived.tzinfo, PicklableFixedOffset)
4514 self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
4515 self.assertEqual(derived.tzname(), 'cookie')
4516
4517 def test_more_bool(self):
4518 # time is always True.
4519 cls = self.theclass
4520
4521 t = cls(0, tzinfo=FixedOffset(-300, ""))
4522 self.assertTrue(t)
4523
4524 t = cls(5, tzinfo=FixedOffset(-300, ""))
4525 self.assertTrue(t)
4526
4527 t = cls(5, tzinfo=FixedOffset(300, ""))
4528 self.assertTrue(t)
4529
4530 t = cls(23, 59, tzinfo=FixedOffset(23*60 + 59, ""))
4531 self.assertTrue(t)
4532
4533 def test_replace(self):
4534 cls = self.theclass
4535 z100 = FixedOffset(100, "+100")
4536 zm200 = FixedOffset(timedelta(minutes=-200), "-200")
4537 args = [1, 2, 3, 4, z100]
4538 base = cls(*args)
4539 self.assertEqual(base.replace(), base)
4540 self.assertEqual(copy.replace(base), base)
4541
4542 changes = (("hour", 5),
4543 ("minute", 6),
4544 ("second", 7),
4545 ("microsecond", 8),
4546 ("tzinfo", zm200))
4547 for i, (name, newval) in enumerate(changes):
4548 newargs = args[:]
4549 newargs[i] = newval
4550 expected = cls(*newargs)
4551 self.assertEqual(base.replace(**{name: newval}), expected)
4552 self.assertEqual(copy.replace(base, **{name: newval}), expected)
4553
4554 # Ensure we can get rid of a tzinfo.
4555 self.assertEqual(base.tzname(), "+100")
4556 base2 = base.replace(tzinfo=None)
4557 self.assertIsNone(base2.tzinfo)
4558 self.assertIsNone(base2.tzname())
4559 base22 = copy.replace(base, tzinfo=None)
4560 self.assertIsNone(base22.tzinfo)
4561 self.assertIsNone(base22.tzname())
4562
4563 # Ensure we can add one.
4564 base3 = base2.replace(tzinfo=z100)
4565 self.assertEqual(base, base3)
4566 self.assertIs(base.tzinfo, base3.tzinfo)
4567 base32 = copy.replace(base22, tzinfo=z100)
4568 self.assertEqual(base, base32)
4569 self.assertIs(base.tzinfo, base32.tzinfo)
4570
4571 # Out of bounds.
4572 base = cls(1)
4573 self.assertRaises(ValueError, base.replace, hour=24)
4574 self.assertRaises(ValueError, base.replace, minute=-1)
4575 self.assertRaises(ValueError, base.replace, second=100)
4576 self.assertRaises(ValueError, base.replace, microsecond=1000000)
4577 self.assertRaises(ValueError, copy.replace, base, hour=24)
4578 self.assertRaises(ValueError, copy.replace, base, minute=-1)
4579 self.assertRaises(ValueError, copy.replace, base, second=100)
4580 self.assertRaises(ValueError, copy.replace, base, microsecond=1000000)
4581
4582 def test_mixed_compare(self):
4583 t1 = self.theclass(1, 2, 3)
4584 t2 = self.theclass(1, 2, 3)
4585 self.assertEqual(t1, t2)
4586 t2 = t2.replace(tzinfo=None)
4587 self.assertEqual(t1, t2)
4588 t2 = t2.replace(tzinfo=FixedOffset(None, ""))
4589 self.assertEqual(t1, t2)
4590 t2 = t2.replace(tzinfo=FixedOffset(0, ""))
4591 self.assertNotEqual(t1, t2)
4592
4593 # In time w/ identical tzinfo objects, utcoffset is ignored.
4594 class Varies(tzinfo):
4595 def __init__(self):
4596 self.offset = timedelta(minutes=22)
4597 def utcoffset(self, t):
4598 self.offset += timedelta(minutes=1)
4599 return self.offset
4600
4601 v = Varies()
4602 t1 = t2.replace(tzinfo=v)
4603 t2 = t2.replace(tzinfo=v)
4604 self.assertEqual(t1.utcoffset(), timedelta(minutes=23))
4605 self.assertEqual(t2.utcoffset(), timedelta(minutes=24))
4606 self.assertEqual(t1, t2)
4607
4608 # But if they're not identical, it isn't ignored.
4609 t2 = t2.replace(tzinfo=Varies())
4610 self.assertTrue(t1 < t2) # t1's offset counter still going up
4611
4612 def test_valuerror_messages(self):
4613 pattern = re.compile(
4614 r"(hour|minute|second|microsecond) must be in \d+\.\.\d+, not \d+"
4615 )
4616 test_cases = [
4617 (12, 30, 90, 9999991), # Microsecond out of range
4618 (12, 30, 90, 000000), # Second out of range
4619 (25, 30, 45, 000000), # Hour out of range
4620 (12, 90, 45, 000000), # Minute out of range
4621 ]
4622 for case in test_cases:
4623 with self.subTest(case):
4624 with self.assertRaisesRegex(ValueError, pattern):
4625 self.theclass(*case)
4626
4627 def test_fromisoformat(self):
4628 time_examples = [
4629 (0, 0, 0, 0),
4630 (23, 59, 59, 999999),
4631 ]
4632
4633 hh = (9, 12, 20)
4634 mm = (5, 30)
4635 ss = (4, 45)
4636 usec = (0, 245000, 678901)
4637
4638 time_examples += list(itertools.product(hh, mm, ss, usec))
4639
4640 tzinfos = [None, timezone.utc,
4641 timezone(timedelta(hours=2)),
4642 timezone(timedelta(hours=6, minutes=27))]
4643
4644 for ttup in time_examples:
4645 for tzi in tzinfos:
4646 t = self.theclass(*ttup, tzinfo=tzi)
4647 tstr = t.isoformat()
4648
4649 with self.subTest(tstr=tstr):
4650 t_rt = self.theclass.fromisoformat(tstr)
4651 self.assertEqual(t, t_rt)
4652
4653 def test_fromisoformat_timezone(self):
4654 base_time = self.theclass(12, 30, 45, 217456)
4655
4656 tzoffsets = [
4657 timedelta(hours=5), timedelta(hours=2),
4658 timedelta(hours=6, minutes=27),
4659 timedelta(hours=12, minutes=32, seconds=30),
4660 timedelta(hours=2, minutes=4, seconds=9, microseconds=123456)
4661 ]
4662
4663 tzoffsets += [-1 * td for td in tzoffsets]
4664
4665 tzinfos = [None, timezone.utc,
4666 timezone(timedelta(hours=0))]
4667
4668 tzinfos += [timezone(td) for td in tzoffsets]
4669
4670 for tzi in tzinfos:
4671 t = base_time.replace(tzinfo=tzi)
4672 tstr = t.isoformat()
4673
4674 with self.subTest(tstr=tstr):
4675 t_rt = self.theclass.fromisoformat(tstr)
4676 assert t == t_rt
4677
4678 def test_fromisoformat_timespecs(self):
4679 time_bases = [
4680 (8, 17, 45, 123456),
4681 (8, 17, 45, 0)
4682 ]
4683
4684 tzinfos = [None, timezone.utc,
4685 timezone(timedelta(hours=-5)),
4686 timezone(timedelta(hours=2)),
4687 timezone(timedelta(hours=6, minutes=27))]
4688
4689 timespecs = ['hours', 'minutes', 'seconds',
4690 'milliseconds', 'microseconds']
4691
4692 for ip, ts in enumerate(timespecs):
4693 for tzi in tzinfos:
4694 for t_tuple in time_bases:
4695 if ts == 'milliseconds':
4696 new_microseconds = 1000 * (t_tuple[-1] // 1000)
4697 t_tuple = t_tuple[0:-1] + (new_microseconds,)
4698
4699 t = self.theclass(*(t_tuple[0:(1 + ip)]), tzinfo=tzi)
4700 tstr = t.isoformat(timespec=ts)
4701 with self.subTest(tstr=tstr):
4702 t_rt = self.theclass.fromisoformat(tstr)
4703 self.assertEqual(t, t_rt)
4704
4705 def test_fromisoformat_fractions(self):
4706 strs = [
4707 ('12:30:45.1', (12, 30, 45, 100000)),
4708 ('12:30:45.12', (12, 30, 45, 120000)),
4709 ('12:30:45.123', (12, 30, 45, 123000)),
4710 ('12:30:45.1234', (12, 30, 45, 123400)),
4711 ('12:30:45.12345', (12, 30, 45, 123450)),
4712 ('12:30:45.123456', (12, 30, 45, 123456)),
4713 ('12:30:45.1234567', (12, 30, 45, 123456)),
4714 ('12:30:45.12345678', (12, 30, 45, 123456)),
4715 ]
4716
4717 for time_str, time_comps in strs:
4718 expected = self.theclass(*time_comps)
4719 actual = self.theclass.fromisoformat(time_str)
4720
4721 self.assertEqual(actual, expected)
4722
4723 def test_fromisoformat_time_examples(self):
4724 examples = [
4725 ('0000', self.theclass(0, 0)),
4726 ('00:00', self.theclass(0, 0)),
4727 ('000000', self.theclass(0, 0)),
4728 ('00:00:00', self.theclass(0, 0)),
4729 ('000000.0', self.theclass(0, 0)),
4730 ('00:00:00.0', self.theclass(0, 0)),
4731 ('000000.000', self.theclass(0, 0)),
4732 ('00:00:00.000', self.theclass(0, 0)),
4733 ('000000.000000', self.theclass(0, 0)),
4734 ('00:00:00.000000', self.theclass(0, 0)),
4735 ('00:00:00,100000', self.theclass(0, 0, 0, 100000)),
4736 ('1200', self.theclass(12, 0)),
4737 ('12:00', self.theclass(12, 0)),
4738 ('120000', self.theclass(12, 0)),
4739 ('12:00:00', self.theclass(12, 0)),
4740 ('120000.0', self.theclass(12, 0)),
4741 ('12:00:00.0', self.theclass(12, 0)),
4742 ('120000.000', self.theclass(12, 0)),
4743 ('12:00:00.000', self.theclass(12, 0)),
4744 ('120000.000000', self.theclass(12, 0)),
4745 ('12:00:00.000000', self.theclass(12, 0)),
4746 ('2359', self.theclass(23, 59)),
4747 ('23:59', self.theclass(23, 59)),
4748 ('235959', self.theclass(23, 59, 59)),
4749 ('23:59:59', self.theclass(23, 59, 59)),
4750 ('235959.9', self.theclass(23, 59, 59, 900000)),
4751 ('23:59:59.9', self.theclass(23, 59, 59, 900000)),
4752 ('235959.999', self.theclass(23, 59, 59, 999000)),
4753 ('23:59:59.999', self.theclass(23, 59, 59, 999000)),
4754 ('235959.999999', self.theclass(23, 59, 59, 999999)),
4755 ('23:59:59.999999', self.theclass(23, 59, 59, 999999)),
4756 ('00:00:00Z', self.theclass(0, 0, tzinfo=timezone.utc)),
4757 ('12:00:00+0000', self.theclass(12, 0, tzinfo=timezone.utc)),
4758 ('12:00:00+00:00', self.theclass(12, 0, tzinfo=timezone.utc)),
4759 ('00:00:00+05',
4760 self.theclass(0, 0, tzinfo=timezone(timedelta(hours=5)))),
4761 ('00:00:00+05:30',
4762 self.theclass(0, 0, tzinfo=timezone(timedelta(hours=5, minutes=30)))),
4763 ('12:00:00-05:00',
4764 self.theclass(12, 0, tzinfo=timezone(timedelta(hours=-5)))),
4765 ('12:00:00-0500',
4766 self.theclass(12, 0, tzinfo=timezone(timedelta(hours=-5)))),
4767 ('00:00:00,000-23:59:59.999999',
4768 self.theclass(0, 0, tzinfo=timezone(-timedelta(hours=23, minutes=59, seconds=59, microseconds=999999)))),
4769 ]
4770
4771 for input_str, expected in examples:
4772 with self.subTest(input_str=input_str):
4773 actual = self.theclass.fromisoformat(input_str)
4774 self.assertEqual(actual, expected)
4775
4776 def test_fromisoformat_fails(self):
4777 bad_strs = [
4778 '', # Empty string
4779 '12\ud80000', # Invalid separator - surrogate char
4780 '12:', # Ends on a separator
4781 '12:30:', # Ends on a separator
4782 '12:30:15.', # Ends on a separator
4783 '1', # Incomplete hours
4784 '12:3', # Incomplete minutes
4785 '12:30:1', # Incomplete seconds
4786 '1a:30:45.334034', # Invalid character in hours
4787 '12:a0:45.334034', # Invalid character in minutes
4788 '12:30:a5.334034', # Invalid character in seconds
4789 '12:30:45.123456+24:30', # Invalid time zone offset
4790 '12:30:45.123456-24:30', # Invalid negative offset
4791 '12:30:45', # Uses full-width unicode colons
4792 '12:30:45.123456a', # Non-numeric data after 6 components
4793 '12:30:45.123456789a', # Non-numeric data after 9 components
4794 '12:30:45․123456', # Uses \u2024 in place of decimal point
4795 '12:30:45a', # Extra at tend of basic time
4796 '12:30:45.123a', # Extra at end of millisecond time
4797 '12:30:45.123456a', # Extra at end of microsecond time
4798 '12:30:45.123456-', # Extra at end of microsecond time
4799 '12:30:45.123456+', # Extra at end of microsecond time
4800 '12:30:45.123456+12:00:30a', # Extra at end of full time
4801 '12.5', # Decimal mark at end of hour
4802 '12:30,5', # Decimal mark at end of minute
4803 '12:30:45.123456Z12:00', # Extra time zone info after Z
4804 '12:30:45:334034', # Invalid microsecond separator
4805 '12:30:45.400 +02:30', # Space between ms and timezone (gh-130959)
4806 '12:30:45.400 ', # Trailing space (gh-130959)
4807 '12:30:45. 400', # Space before fraction (gh-130959)
4808 ]
4809
4810 for bad_str in bad_strs:
4811 with self.subTest(bad_str=bad_str):
4812 with self.assertRaises(ValueError):
4813 self.theclass.fromisoformat(bad_str)
4814
4815 def test_fromisoformat_fails_typeerror(self):
4816 # Test the fromisoformat fails when passed the wrong type
4817 bad_types = [b'12:30:45', None, io.StringIO('12:30:45')]
4818
4819 for bad_type in bad_types:
4820 with self.assertRaises(TypeError):
4821 self.theclass.fromisoformat(bad_type)
4822
4823 def test_fromisoformat_subclass(self):
4824 class TimeSubclass(self.theclass):
4825 pass
4826
4827 tsc = TimeSubclass(12, 14, 45, 203745, tzinfo=timezone.utc)
4828 tsc_rt = TimeSubclass.fromisoformat(tsc.isoformat())
4829
4830 self.assertEqual(tsc, tsc_rt)
4831 self.assertIsInstance(tsc_rt, TimeSubclass)
4832
4833 def test_subclass_timetz(self):
4834
4835 class C(self.theclass):
4836 theAnswer = 42
4837
4838 def __new__(cls, *args, **kws):
4839 temp = kws.copy()
4840 extra = temp.pop('extra')
4841 result = self.theclass.__new__(cls, *args, **temp)
4842 result.extra = extra
4843 return result
4844
4845 def newmeth(self, start):
4846 return start + self.hour + self.second
4847
4848 args = 4, 5, 6, 500, FixedOffset(-300, "EST", 1)
4849
4850 dt1 = self.theclass(*args)
4851 dt2 = C(*args, **{'extra': 7})
4852
4853 self.assertEqual(dt2.__class__, C)
4854 self.assertEqual(dt2.theAnswer, 42)
4855 self.assertEqual(dt2.extra, 7)
4856 self.assertEqual(dt1.utcoffset(), dt2.utcoffset())
4857 self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.second - 7)
4858
4859
4860 # Testing datetime objects with a non-None tzinfo.
4861
4862 class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
4863 theclass = datetime
4864
4865 def test_trivial(self):
4866 dt = self.theclass(1, 2, 3, 4, 5, 6, 7)
4867 self.assertEqual(dt.year, 1)
4868 self.assertEqual(dt.month, 2)
4869 self.assertEqual(dt.day, 3)
4870 self.assertEqual(dt.hour, 4)
4871 self.assertEqual(dt.minute, 5)
4872 self.assertEqual(dt.second, 6)
4873 self.assertEqual(dt.microsecond, 7)
4874 self.assertEqual(dt.tzinfo, None)
4875
4876 def test_even_more_compare(self):
4877 # The test_compare() and test_more_compare() inherited from TestDate
4878 # and TestDateTime covered non-tzinfo cases.
4879
4880 # Smallest possible after UTC adjustment.
4881 t1 = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, ""))
4882 # Largest possible after UTC adjustment.
4883 t2 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
4884 tzinfo=FixedOffset(-1439, ""))
4885
4886 # Make sure those compare correctly, and w/o overflow.
4887 self.assertTrue(t1 < t2)
4888 self.assertTrue(t1 != t2)
4889 self.assertTrue(t2 > t1)
4890
4891 self.assertEqual(t1, t1)
4892 self.assertEqual(t2, t2)
4893
4894 # Equal after adjustment.
4895 t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""))
4896 t2 = self.theclass(2, 1, 1, 3, 13, tzinfo=FixedOffset(3*60+13+2, ""))
4897 self.assertEqual(t1, t2)
4898
4899 # Change t1 not to subtract a minute, and t1 should be larger.
4900 t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(0, ""))
4901 self.assertTrue(t1 > t2)
4902
4903 # Change t1 to subtract 2 minutes, and t1 should be smaller.
4904 t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(2, ""))
4905 self.assertTrue(t1 < t2)
4906
4907 # Back to the original t1, but make seconds resolve it.
4908 t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""),
4909 second=1)
4910 self.assertTrue(t1 > t2)
4911
4912 # Likewise, but make microseconds resolve it.
4913 t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""),
4914 microsecond=1)
4915 self.assertTrue(t1 > t2)
4916
4917 # Make t2 naive and it should differ.
4918 t2 = self.theclass.min
4919 self.assertNotEqual(t1, t2)
4920 self.assertEqual(t2, t2)
4921 # and > comparison should fail
4922 with self.assertRaises(TypeError):
4923 t1 > t2
4924
4925 # It's also naive if it has tzinfo but tzinfo.utcoffset() is None.
4926 class Naive(tzinfo):
4927 def utcoffset(self, dt): return None
4928 t2 = self.theclass(5, 6, 7, tzinfo=Naive())
4929 self.assertNotEqual(t1, t2)
4930 self.assertEqual(t2, t2)
4931
4932 # OTOH, it's OK to compare two of these mixing the two ways of being
4933 # naive.
4934 t1 = self.theclass(5, 6, 7)
4935 self.assertEqual(t1, t2)
4936
4937 # Try a bogus uctoffset.
4938 class Bogus(tzinfo):
4939 def utcoffset(self, dt):
4940 return timedelta(minutes=1440) # out of bounds
4941 t1 = self.theclass(2, 2, 2, tzinfo=Bogus())
4942 t2 = self.theclass(2, 2, 2, tzinfo=FixedOffset(0, ""))
4943 self.assertRaises(ValueError, lambda: t1 == t2)
4944
4945 def test_pickling(self):
4946 # Try one without a tzinfo.
4947 args = 6, 7, 23, 20, 59, 1, 64**2
4948 orig = self.theclass(*args)
4949 for pickler, unpickler, proto in pickle_choices:
4950 green = pickler.dumps(orig, proto)
4951 derived = unpickler.loads(green)
4952 self.assertEqual(orig, derived)
4953 self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2))
4954
4955 # Try one with a tzinfo.
4956 tinfo = PicklableFixedOffset(-300, 'cookie')
4957 orig = self.theclass(*args, **{'tzinfo': tinfo})
4958 derived = self.theclass(1, 1, 1, tzinfo=FixedOffset(0, "", 0))
4959 for pickler, unpickler, proto in pickle_choices:
4960 green = pickler.dumps(orig, proto)
4961 derived = unpickler.loads(green)
4962 self.assertEqual(orig, derived)
4963 self.assertIsInstance(derived.tzinfo, PicklableFixedOffset)
4964 self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
4965 self.assertEqual(derived.tzname(), 'cookie')
4966 self.assertEqual(orig.__reduce__(), orig.__reduce_ex__(2))
4967
4968 def test_compat_unpickle(self):
4969 tests = [
4970 b'cdatetime\ndatetime\n'
4971 b"(S'\\x07\\xdf\\x0b\\x1b\\x14;\\x01\\x01\\xe2@'\n"
4972 b'ctest.datetimetester\nPicklableFixedOffset\n(tR'
4973 b"(dS'_FixedOffset__offset'\ncdatetime\ntimedelta\n"
4974 b'(I-1\nI68400\nI0\ntRs'
4975 b"S'_FixedOffset__dstoffset'\nNs"
4976 b"S'_FixedOffset__name'\nS'cookie'\nsbtR.",
4977
4978 b'cdatetime\ndatetime\n'
4979 b'(U\n\x07\xdf\x0b\x1b\x14;\x01\x01\xe2@'
4980 b'ctest.datetimetester\nPicklableFixedOffset\n)R'
4981 b'}(U\x14_FixedOffset__offsetcdatetime\ntimedelta\n'
4982 b'(J\xff\xff\xff\xffJ0\x0b\x01\x00K\x00tR'
4983 b'U\x17_FixedOffset__dstoffsetN'
4984 b'U\x12_FixedOffset__nameU\x06cookieubtR.',
4985
4986 b'\x80\x02cdatetime\ndatetime\n'
4987 b'U\n\x07\xdf\x0b\x1b\x14;\x01\x01\xe2@'
4988 b'ctest.datetimetester\nPicklableFixedOffset\n)R'
4989 b'}(U\x14_FixedOffset__offsetcdatetime\ntimedelta\n'
4990 b'J\xff\xff\xff\xffJ0\x0b\x01\x00K\x00\x87R'
4991 b'U\x17_FixedOffset__dstoffsetN'
4992 b'U\x12_FixedOffset__nameU\x06cookieub\x86R.',
4993 ]
4994 args = 2015, 11, 27, 20, 59, 1, 123456
4995 tinfo = PicklableFixedOffset(-300, 'cookie')
4996 expected = self.theclass(*args, **{'tzinfo': tinfo})
4997 for data in tests:
4998 for loads in pickle_loads:
4999 derived = loads(data, encoding='latin1')
5000 self.assertEqual(derived, expected)
5001 self.assertIsInstance(derived.tzinfo, PicklableFixedOffset)
5002 self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
5003 self.assertEqual(derived.tzname(), 'cookie')
5004
5005 def test_extreme_hashes(self):
5006 # If an attempt is made to hash these via subtracting the offset
5007 # then hashing a datetime object, OverflowError results. The
5008 # Python implementation used to blow up here.
5009 t = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, ""))
5010 hash(t)
5011 t = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
5012 tzinfo=FixedOffset(-1439, ""))
5013 hash(t)
5014
5015 # OTOH, an OOB offset should blow up.
5016 t = self.theclass(5, 5, 5, tzinfo=FixedOffset(-1440, ""))
5017 self.assertRaises(ValueError, hash, t)
5018
5019 def test_zones(self):
5020 est = FixedOffset(-300, "EST")
5021 utc = FixedOffset(0, "UTC")
5022 met = FixedOffset(60, "MET")
5023 t1 = datetime(2002, 3, 19, 7, 47, tzinfo=est)
5024 t2 = datetime(2002, 3, 19, 12, 47, tzinfo=utc)
5025 t3 = datetime(2002, 3, 19, 13, 47, tzinfo=met)
5026 self.assertEqual(t1.tzinfo, est)
5027 self.assertEqual(t2.tzinfo, utc)
5028 self.assertEqual(t3.tzinfo, met)
5029 self.assertEqual(t1.utcoffset(), timedelta(minutes=-300))
5030 self.assertEqual(t2.utcoffset(), timedelta(minutes=0))
5031 self.assertEqual(t3.utcoffset(), timedelta(minutes=60))
5032 self.assertEqual(t1.tzname(), "EST")
5033 self.assertEqual(t2.tzname(), "UTC")
5034 self.assertEqual(t3.tzname(), "MET")
5035 self.assertEqual(hash(t1), hash(t2))
5036 self.assertEqual(hash(t1), hash(t3))
5037 self.assertEqual(hash(t2), hash(t3))
5038 self.assertEqual(t1, t2)
5039 self.assertEqual(t1, t3)
5040 self.assertEqual(t2, t3)
5041 self.assertEqual(str(t1), "2002-03-19 07:47:00-05:00")
5042 self.assertEqual(str(t2), "2002-03-19 12:47:00+00:00")
5043 self.assertEqual(str(t3), "2002-03-19 13:47:00+01:00")
5044 d = 'datetime.datetime(2002, 3, 19, '
5045 self.assertEqual(repr(t1), d + "7, 47, tzinfo=est)")
5046 self.assertEqual(repr(t2), d + "12, 47, tzinfo=utc)")
5047 self.assertEqual(repr(t3), d + "13, 47, tzinfo=met)")
5048
5049 def test_combine(self):
5050 met = FixedOffset(60, "MET")
5051 d = date(2002, 3, 4)
5052 tz = time(18, 45, 3, 1234, tzinfo=met)
5053 dt = datetime.combine(d, tz)
5054 self.assertEqual(dt, datetime(2002, 3, 4, 18, 45, 3, 1234,
5055 tzinfo=met))
5056
5057 def test_extract(self):
5058 met = FixedOffset(60, "MET")
5059 dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234, tzinfo=met)
5060 self.assertEqual(dt.date(), date(2002, 3, 4))
5061 self.assertEqual(dt.time(), time(18, 45, 3, 1234))
5062 self.assertEqual(dt.timetz(), time(18, 45, 3, 1234, tzinfo=met))
5063
5064 def test_tz_aware_arithmetic(self):
5065 now = self.theclass.now()
5066 tz55 = FixedOffset(-330, "west 5:30")
5067 timeaware = now.time().replace(tzinfo=tz55)
5068 nowaware = self.theclass.combine(now.date(), timeaware)
5069 self.assertIs(nowaware.tzinfo, tz55)
5070 self.assertEqual(nowaware.timetz(), timeaware)
5071
5072 # Can't mix aware and non-aware.
5073 self.assertRaises(TypeError, lambda: now - nowaware)
5074 self.assertRaises(TypeError, lambda: nowaware - now)
5075
5076 # And adding datetime's doesn't make sense, aware or not.
5077 self.assertRaises(TypeError, lambda: now + nowaware)
5078 self.assertRaises(TypeError, lambda: nowaware + now)
5079 self.assertRaises(TypeError, lambda: nowaware + nowaware)
5080
5081 # Subtracting should yield 0.
5082 self.assertEqual(now - now, timedelta(0))
5083 self.assertEqual(nowaware - nowaware, timedelta(0))
5084
5085 # Adding a delta should preserve tzinfo.
5086 delta = timedelta(weeks=1, minutes=12, microseconds=5678)
5087 nowawareplus = nowaware + delta
5088 self.assertIs(nowaware.tzinfo, tz55)
5089 nowawareplus2 = delta + nowaware
5090 self.assertIs(nowawareplus2.tzinfo, tz55)
5091 self.assertEqual(nowawareplus, nowawareplus2)
5092
5093 # that - delta should be what we started with, and that - what we
5094 # started with should be delta.
5095 diff = nowawareplus - delta
5096 self.assertIs(diff.tzinfo, tz55)
5097 self.assertEqual(nowaware, diff)
5098 self.assertRaises(TypeError, lambda: delta - nowawareplus)
5099 self.assertEqual(nowawareplus - nowaware, delta)
5100
5101 # Make up a random timezone.
5102 tzr = FixedOffset(random.randrange(-1439, 1440), "randomtimezone")
5103 # Attach it to nowawareplus.
5104 nowawareplus = nowawareplus.replace(tzinfo=tzr)
5105 self.assertIs(nowawareplus.tzinfo, tzr)
5106 # Make sure the difference takes the timezone adjustments into account.
5107 got = nowaware - nowawareplus
5108 # Expected: (nowaware base - nowaware offset) -
5109 # (nowawareplus base - nowawareplus offset) =
5110 # (nowaware base - nowawareplus base) +
5111 # (nowawareplus offset - nowaware offset) =
5112 # -delta + nowawareplus offset - nowaware offset
5113 expected = nowawareplus.utcoffset() - nowaware.utcoffset() - delta
5114 self.assertEqual(got, expected)
5115
5116 # Try max possible difference.
5117 min = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "min"))
5118 max = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
5119 tzinfo=FixedOffset(-1439, "max"))
5120 maxdiff = max - min
5121 self.assertEqual(maxdiff, self.theclass.max - self.theclass.min +
5122 timedelta(minutes=2*1439))
5123 # Different tzinfo, but the same offset
5124 tza = timezone(HOUR, 'A')
5125 tzb = timezone(HOUR, 'B')
5126 delta = min.replace(tzinfo=tza) - max.replace(tzinfo=tzb)
5127 self.assertEqual(delta, self.theclass.min - self.theclass.max)
5128
5129 def test_tzinfo_now(self):
5130 meth = self.theclass.now
5131 # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
5132 base = meth()
5133 # Try with and without naming the keyword.
5134 off42 = FixedOffset(42, "42")
5135 another = meth(off42)
5136 again = meth(tz=off42)
5137 self.assertIs(another.tzinfo, again.tzinfo)
5138 self.assertEqual(another.utcoffset(), timedelta(minutes=42))
5139 # Bad argument with and w/o naming the keyword.
5140 self.assertRaises(TypeError, meth, 16)
5141 self.assertRaises(TypeError, meth, tzinfo=16)
5142 # Bad keyword name.
5143 self.assertRaises(TypeError, meth, tinfo=off42)
5144 # Too many args.
5145 self.assertRaises(TypeError, meth, off42, off42)
5146
5147 # We don't know which time zone we're in, and don't have a tzinfo
5148 # class to represent it, so seeing whether a tz argument actually
5149 # does a conversion is tricky.
5150 utc = FixedOffset(0, "utc", 0)
5151 for weirdtz in [FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0),
5152 timezone(timedelta(hours=15, minutes=58), "weirdtz"),]:
5153 for dummy in range(3):
5154 now = datetime.now(weirdtz)
5155 self.assertIs(now.tzinfo, weirdtz)
5156 with self.assertWarns(DeprecationWarning):
5157 utcnow = datetime.utcnow().replace(tzinfo=utc)
5158 now2 = utcnow.astimezone(weirdtz)
5159 if abs(now - now2) < timedelta(seconds=30):
5160 break
5161 # Else the code is broken, or more than 30 seconds passed between
5162 # calls; assuming the latter, just try again.
5163 else:
5164 # Three strikes and we're out.
5165 self.fail("utcnow(), now(tz), or astimezone() may be broken")
5166
5167 def test_tzinfo_fromtimestamp(self):
5168 import time
5169 meth = self.theclass.fromtimestamp
5170 ts = time.time()
5171 # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
5172 base = meth(ts)
5173 # Try with and without naming the keyword.
5174 off42 = FixedOffset(42, "42")
5175 another = meth(ts, off42)
5176 again = meth(ts, tz=off42)
5177 self.assertIs(another.tzinfo, again.tzinfo)
5178 self.assertEqual(another.utcoffset(), timedelta(minutes=42))
5179 # Bad argument with and w/o naming the keyword.
5180 self.assertRaises(TypeError, meth, ts, 16)
5181 self.assertRaises(TypeError, meth, ts, tzinfo=16)
5182 # Bad keyword name.
5183 self.assertRaises(TypeError, meth, ts, tinfo=off42)
5184 # Too many args.
5185 self.assertRaises(TypeError, meth, ts, off42, off42)
5186 # Too few args.
5187 self.assertRaises(TypeError, meth)
5188
5189 # Try to make sure tz= actually does some conversion.
5190 timestamp = 1000000000
5191 with self.assertWarns(DeprecationWarning):
5192 utcdatetime = datetime.utcfromtimestamp(timestamp)
5193 # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take.
5194 # But on some flavor of Mac, it's nowhere near that. So we can't have
5195 # any idea here what time that actually is, we can only test that
5196 # relative changes match.
5197 utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero
5198 tz = FixedOffset(utcoffset, "tz", 0)
5199 expected = utcdatetime + utcoffset
5200 got = datetime.fromtimestamp(timestamp, tz)
5201 self.assertEqual(expected, got.replace(tzinfo=None))
5202
5203 def test_tzinfo_utcnow(self):
5204 meth = self.theclass.utcnow
5205 # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
5206 with self.assertWarns(DeprecationWarning):
5207 base = meth()
5208 # Try with and without naming the keyword; for whatever reason,
5209 # utcnow() doesn't accept a tzinfo argument.
5210 off42 = FixedOffset(42, "42")
5211 self.assertRaises(TypeError, meth, off42)
5212 self.assertRaises(TypeError, meth, tzinfo=off42)
5213
5214 def test_tzinfo_utcfromtimestamp(self):
5215 import time
5216 meth = self.theclass.utcfromtimestamp
5217 ts = time.time()
5218 # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
5219 with self.assertWarns(DeprecationWarning):
5220 base = meth(ts)
5221 # Try with and without naming the keyword; for whatever reason,
5222 # utcfromtimestamp() doesn't accept a tzinfo argument.
5223 off42 = FixedOffset(42, "42")
5224 with warnings.catch_warnings(category=DeprecationWarning):
5225 warnings.simplefilter("ignore", category=DeprecationWarning)
5226 self.assertRaises(TypeError, meth, ts, off42)
5227 self.assertRaises(TypeError, meth, ts, tzinfo=off42)
5228
5229 def test_tzinfo_timetuple(self):
5230 # TestDateTime tested most of this. datetime adds a twist to the
5231 # DST flag.
5232 class DST(tzinfo):
5233 def __init__(self, dstvalue):
5234 if isinstance(dstvalue, int):
5235 dstvalue = timedelta(minutes=dstvalue)
5236 self.dstvalue = dstvalue
5237 def dst(self, dt):
5238 return self.dstvalue
5239
5240 cls = self.theclass
5241 for dstvalue, flag in (-33, 1), (33, 1), (0, 0), (None, -1):
5242 d = cls(1, 1, 1, 10, 20, 30, 40, tzinfo=DST(dstvalue))
5243 t = d.timetuple()
5244 self.assertEqual(1, t.tm_year)
5245 self.assertEqual(1, t.tm_mon)
5246 self.assertEqual(1, t.tm_mday)
5247 self.assertEqual(10, t.tm_hour)
5248 self.assertEqual(20, t.tm_min)
5249 self.assertEqual(30, t.tm_sec)
5250 self.assertEqual(0, t.tm_wday)
5251 self.assertEqual(1, t.tm_yday)
5252 self.assertEqual(flag, t.tm_isdst)
5253
5254 # dst() returns wrong type.
5255 self.assertRaises(TypeError, cls(1, 1, 1, tzinfo=DST("x")).timetuple)
5256
5257 # dst() at the edge.
5258 self.assertEqual(cls(1,1,1, tzinfo=DST(1439)).timetuple().tm_isdst, 1)
5259 self.assertEqual(cls(1,1,1, tzinfo=DST(-1439)).timetuple().tm_isdst, 1)
5260
5261 # dst() out of range.
5262 self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(1440)).timetuple)
5263 self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(-1440)).timetuple)
5264
5265 def test_utctimetuple(self):
5266 class DST(tzinfo):
5267 def __init__(self, dstvalue=0):
5268 if isinstance(dstvalue, int):
5269 dstvalue = timedelta(minutes=dstvalue)
5270 self.dstvalue = dstvalue
5271 def dst(self, dt):
5272 return self.dstvalue
5273
5274 cls = self.theclass
5275 # This can't work: DST didn't implement utcoffset.
5276 self.assertRaises(NotImplementedError,
5277 cls(1, 1, 1, tzinfo=DST(0)).utcoffset)
5278
5279 class UOFS(DST):
5280 def __init__(self, uofs, dofs=None):
5281 DST.__init__(self, dofs)
5282 self.uofs = timedelta(minutes=uofs)
5283 def utcoffset(self, dt):
5284 return self.uofs
5285
5286 for dstvalue in -33, 33, 0, None:
5287 d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=UOFS(-53, dstvalue))
5288 t = d.utctimetuple()
5289 self.assertEqual(d.year, t.tm_year)
5290 self.assertEqual(d.month, t.tm_mon)
5291 self.assertEqual(d.day, t.tm_mday)
5292 self.assertEqual(11, t.tm_hour) # 20mm + 53mm = 1hn + 13mm
5293 self.assertEqual(13, t.tm_min)
5294 self.assertEqual(d.second, t.tm_sec)
5295 self.assertEqual(d.weekday(), t.tm_wday)
5296 self.assertEqual(d.toordinal() - date(1, 1, 1).toordinal() + 1,
5297 t.tm_yday)
5298 # Ensure tm_isdst is 0 regardless of what dst() says: DST
5299 # is never in effect for a UTC time.
5300 self.assertEqual(0, t.tm_isdst)
5301
5302 # For naive datetime, utctimetuple == timetuple except for isdst
5303 d = cls(1, 2, 3, 10, 20, 30, 40)
5304 t = d.utctimetuple()
5305 self.assertEqual(t[:-1], d.timetuple()[:-1])
5306 self.assertEqual(0, t.tm_isdst)
5307 # Same if utcoffset is None
5308 class NOFS(DST):
5309 def utcoffset(self, dt):
5310 return None
5311 d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=NOFS())
5312 t = d.utctimetuple()
5313 self.assertEqual(t[:-1], d.timetuple()[:-1])
5314 self.assertEqual(0, t.tm_isdst)
5315 # Check that bad tzinfo is detected
5316 class BOFS(DST):
5317 def utcoffset(self, dt):
5318 return "EST"
5319 d = cls(1, 2, 3, 10, 20, 30, 40, tzinfo=BOFS())
5320 self.assertRaises(TypeError, d.utctimetuple)
5321
5322 # Check that utctimetuple() is the same as
5323 # astimezone(utc).timetuple()
5324 d = cls(2010, 11, 13, 14, 15, 16, 171819)
5325 for tz in [timezone.min, timezone.utc, timezone.max]:
5326 dtz = d.replace(tzinfo=tz)
5327 self.assertEqual(dtz.utctimetuple()[:-1],
5328 dtz.astimezone(timezone.utc).timetuple()[:-1])
5329 # At the edges, UTC adjustment can produce years out-of-range
5330 # for a datetime object. Ensure that an OverflowError is
5331 # raised.
5332 tiny = cls(MINYEAR, 1, 1, 0, 0, 37, tzinfo=UOFS(1439))
5333 # That goes back 1 minute less than a full day.
5334 self.assertRaises(OverflowError, tiny.utctimetuple)
5335
5336 huge = cls(MAXYEAR, 12, 31, 23, 59, 37, 999999, tzinfo=UOFS(-1439))
5337 # That goes forward 1 minute less than a full day.
5338 self.assertRaises(OverflowError, huge.utctimetuple)
5339 # More overflow cases
5340 tiny = cls.min.replace(tzinfo=timezone(MINUTE))
5341 self.assertRaises(OverflowError, tiny.utctimetuple)
5342 huge = cls.max.replace(tzinfo=timezone(-MINUTE))
5343 self.assertRaises(OverflowError, huge.utctimetuple)
5344
5345 def test_tzinfo_isoformat(self):
5346 zero = FixedOffset(0, "+00:00")
5347 plus = FixedOffset(220, "+03:40")
5348 minus = FixedOffset(-231, "-03:51")
5349 unknown = FixedOffset(None, "")
5350
5351 cls = self.theclass
5352 datestr = '0001-02-03'
5353 for ofs in None, zero, plus, minus, unknown:
5354 for us in 0, 987001:
5355 d = cls(1, 2, 3, 4, 5, 59, us, tzinfo=ofs)
5356 timestr = '04:05:59' + (us and '.987001' or '')
5357 ofsstr = ofs is not None and d.tzname() or ''
5358 tailstr = timestr + ofsstr
5359 iso = d.isoformat()
5360 self.assertEqual(iso, datestr + 'T' + tailstr)
5361 self.assertEqual(iso, d.isoformat('T'))
5362 self.assertEqual(d.isoformat('k'), datestr + 'k' + tailstr)
5363 self.assertEqual(d.isoformat('\u1234'), datestr + '\u1234' + tailstr)
5364 self.assertEqual(str(d), datestr + ' ' + tailstr)
5365
5366 def test_replace(self):
5367 cls = self.theclass
5368 z100 = FixedOffset(100, "+100")
5369 zm200 = FixedOffset(timedelta(minutes=-200), "-200")
5370 args = [1, 2, 3, 4, 5, 6, 7, z100]
5371 base = cls(*args)
5372 self.assertEqual(base.replace(), base)
5373 self.assertEqual(copy.replace(base), base)
5374
5375 changes = (("year", 2),
5376 ("month", 3),
5377 ("day", 4),
5378 ("hour", 5),
5379 ("minute", 6),
5380 ("second", 7),
5381 ("microsecond", 8),
5382 ("tzinfo", zm200))
5383 for i, (name, newval) in enumerate(changes):
5384 newargs = args[:]
5385 newargs[i] = newval
5386 expected = cls(*newargs)
5387 self.assertEqual(base.replace(**{name: newval}), expected)
5388 self.assertEqual(copy.replace(base, **{name: newval}), expected)
5389
5390 # Ensure we can get rid of a tzinfo.
5391 self.assertEqual(base.tzname(), "+100")
5392 base2 = base.replace(tzinfo=None)
5393 self.assertIsNone(base2.tzinfo)
5394 self.assertIsNone(base2.tzname())
5395 base22 = copy.replace(base, tzinfo=None)
5396 self.assertIsNone(base22.tzinfo)
5397 self.assertIsNone(base22.tzname())
5398
5399 # Ensure we can add one.
5400 base3 = base2.replace(tzinfo=z100)
5401 self.assertEqual(base, base3)
5402 self.assertIs(base.tzinfo, base3.tzinfo)
5403 base32 = copy.replace(base22, tzinfo=z100)
5404 self.assertEqual(base, base32)
5405 self.assertIs(base.tzinfo, base32.tzinfo)
5406
5407 # Out of bounds.
5408 base = cls(2000, 2, 29)
5409 self.assertRaises(ValueError, base.replace, year=2001)
5410 self.assertRaises(ValueError, copy.replace, base, year=2001)
5411
5412 def test_more_astimezone(self):
5413 # The inherited test_astimezone covered some trivial and error cases.
5414 fnone = FixedOffset(None, "None")
5415 f44m = FixedOffset(44, "44")
5416 fm5h = FixedOffset(-timedelta(hours=5), "m300")
5417
5418 dt = self.theclass.now(tz=f44m)
5419 self.assertIs(dt.tzinfo, f44m)
5420 # Replacing with degenerate tzinfo raises an exception.
5421 self.assertRaises(ValueError, dt.astimezone, fnone)
5422 # Replacing with same tzinfo makes no change.
5423 x = dt.astimezone(dt.tzinfo)
5424 self.assertIs(x.tzinfo, f44m)
5425 self.assertEqual(x.date(), dt.date())
5426 self.assertEqual(x.time(), dt.time())
5427
5428 # Replacing with different tzinfo does adjust.
5429 got = dt.astimezone(fm5h)
5430 self.assertIs(got.tzinfo, fm5h)
5431 self.assertEqual(got.utcoffset(), timedelta(hours=-5))
5432 expected = dt - dt.utcoffset() # in effect, convert to UTC
5433 expected += fm5h.utcoffset(dt) # and from there to local time
5434 expected = expected.replace(tzinfo=fm5h) # and attach new tzinfo
5435 self.assertEqual(got.date(), expected.date())
5436 self.assertEqual(got.time(), expected.time())
5437 self.assertEqual(got.timetz(), expected.timetz())
5438 self.assertIs(got.tzinfo, expected.tzinfo)
5439 self.assertEqual(got, expected)
5440
5441 @support.run_with_tz('UTC')
5442 def test_astimezone_default_utc(self):
5443 dt = self.theclass.now(timezone.utc)
5444 self.assertEqual(dt.astimezone(None), dt)
5445 self.assertEqual(dt.astimezone(), dt)
5446
5447 # Note that offset in TZ variable has the opposite sign to that
5448 # produced by %z directive.
5449 @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0')
5450 def test_astimezone_default_eastern(self):
5451 dt = self.theclass(2012, 11, 4, 6, 30, tzinfo=timezone.utc)
5452 local = dt.astimezone()
5453 self.assertEqual(dt, local)
5454 self.assertEqual(local.strftime("%z %Z"), "-0500 EST")
5455 dt = self.theclass(2012, 11, 4, 5, 30, tzinfo=timezone.utc)
5456 local = dt.astimezone()
5457 self.assertEqual(dt, local)
5458 self.assertEqual(local.strftime("%z %Z"), "-0400 EDT")
5459
5460 @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0')
5461 def test_astimezone_default_near_fold(self):
5462 # Issue #26616.
5463 u = datetime(2015, 11, 1, 5, tzinfo=timezone.utc)
5464 t = u.astimezone()
5465 s = t.astimezone()
5466 self.assertEqual(t.tzinfo, s.tzinfo)
5467
5468 def test_aware_subtract(self):
5469 cls = self.theclass
5470
5471 # Ensure that utcoffset() is ignored when the operands have the
5472 # same tzinfo member.
5473 class OperandDependentOffset(tzinfo):
5474 def utcoffset(self, t):
5475 if t.minute < 10:
5476 # d0 and d1 equal after adjustment
5477 return timedelta(minutes=t.minute)
5478 else:
5479 # d2 off in the weeds
5480 return timedelta(minutes=59)
5481
5482 base = cls(8, 9, 10, 11, 12, 13, 14, tzinfo=OperandDependentOffset())
5483 d0 = base.replace(minute=3)
5484 d1 = base.replace(minute=9)
5485 d2 = base.replace(minute=11)
5486 for x in d0, d1, d2:
5487 for y in d0, d1, d2:
5488 got = x - y
5489 expected = timedelta(minutes=x.minute - y.minute)
5490 self.assertEqual(got, expected)
5491
5492 # OTOH, if the tzinfo members are distinct, utcoffsets aren't
5493 # ignored.
5494 base = cls(8, 9, 10, 11, 12, 13, 14)
5495 d0 = base.replace(minute=3, tzinfo=OperandDependentOffset())
5496 d1 = base.replace(minute=9, tzinfo=OperandDependentOffset())
5497 d2 = base.replace(minute=11, tzinfo=OperandDependentOffset())
5498 for x in d0, d1, d2:
5499 for y in d0, d1, d2:
5500 got = x - y
5501 if (x is d0 or x is d1) and (y is d0 or y is d1):
5502 expected = timedelta(0)
5503 elif x is y is d2:
5504 expected = timedelta(0)
5505 elif x is d2:
5506 expected = timedelta(minutes=(11-59)-0)
5507 else:
5508 assert y is d2
5509 expected = timedelta(minutes=0-(11-59))
5510 self.assertEqual(got, expected)
5511
5512 def test_mixed_compare(self):
5513 t1 = datetime(1, 2, 3, 4, 5, 6, 7)
5514 t2 = datetime(1, 2, 3, 4, 5, 6, 7)
5515 self.assertEqual(t1, t2)
5516 t2 = t2.replace(tzinfo=None)
5517 self.assertEqual(t1, t2)
5518 t2 = t2.replace(tzinfo=FixedOffset(None, ""))
5519 self.assertEqual(t1, t2)
5520 t2 = t2.replace(tzinfo=FixedOffset(0, ""))
5521 self.assertNotEqual(t1, t2)
5522
5523 # In datetime w/ identical tzinfo objects, utcoffset is ignored.
5524 class Varies(tzinfo):
5525 def __init__(self):
5526 self.offset = timedelta(minutes=22)
5527 def utcoffset(self, t):
5528 self.offset += timedelta(minutes=1)
5529 return self.offset
5530
5531 v = Varies()
5532 t1 = t2.replace(tzinfo=v)
5533 t2 = t2.replace(tzinfo=v)
5534 self.assertEqual(t1.utcoffset(), timedelta(minutes=23))
5535 self.assertEqual(t2.utcoffset(), timedelta(minutes=24))
5536 self.assertEqual(t1, t2)
5537
5538 # But if they're not identical, it isn't ignored.
5539 t2 = t2.replace(tzinfo=Varies())
5540 self.assertTrue(t1 < t2) # t1's offset counter still going up
5541
5542 def test_subclass_datetimetz(self):
5543
5544 class C(self.theclass):
5545 theAnswer = 42
5546
5547 def __new__(cls, *args, **kws):
5548 temp = kws.copy()
5549 extra = temp.pop('extra')
5550 result = self.theclass.__new__(cls, *args, **temp)
5551 result.extra = extra
5552 return result
5553
5554 def newmeth(self, start):
5555 return start + self.hour + self.year
5556
5557 args = 2002, 12, 31, 4, 5, 6, 500, FixedOffset(-300, "EST", 1)
5558
5559 dt1 = self.theclass(*args)
5560 dt2 = C(*args, **{'extra': 7})
5561
5562 self.assertEqual(dt2.__class__, C)
5563 self.assertEqual(dt2.theAnswer, 42)
5564 self.assertEqual(dt2.extra, 7)
5565 self.assertEqual(dt1.utcoffset(), dt2.utcoffset())
5566 self.assertEqual(dt2.newmeth(-7), dt1.hour + dt1.year - 7)
5567
5568 # Pain to set up DST-aware tzinfo classes.
5569
5570 def first_sunday_on_or_after(dt):
5571 days_to_go = 6 - dt.weekday()
5572 if days_to_go:
5573 dt += timedelta(days_to_go)
5574 return dt
5575
5576 ZERO = timedelta(0)
5577 MINUTE = timedelta(minutes=1)
5578 HOUR = timedelta(hours=1)
5579 DAY = timedelta(days=1)
5580 # In the US, DST starts at 2am (standard time) on the first Sunday in April.
5581 DSTSTART = datetime(1, 4, 1, 2)
5582 # and ends at 2am (DST time; 1am standard time) on the last Sunday of Oct,
5583 # which is the first Sunday on or after Oct 25. Because we view 1:MM as
5584 # being standard time on that day, there is no spelling in local time of
5585 # the last hour of DST (that's 1:MM DST, but 1:MM is taken as standard time).
5586 DSTEND = datetime(1, 10, 25, 1)
5587
5588 class USTimeZone(tzinfo):
5589
5590 def __init__(self, hours, reprname, stdname, dstname):
5591 self.stdoffset = timedelta(hours=hours)
5592 self.reprname = reprname
5593 self.stdname = stdname
5594 self.dstname = dstname
5595
5596 def __repr__(self):
5597 return self.reprname
5598
5599 def tzname(self, dt):
5600 if self.dst(dt):
5601 return self.dstname
5602 else:
5603 return self.stdname
5604
5605 def utcoffset(self, dt):
5606 return self.stdoffset + self.dst(dt)
5607
5608 def dst(self, dt):
5609 if dt is None or dt.tzinfo is None:
5610 # An exception instead may be sensible here, in one or more of
5611 # the cases.
5612 return ZERO
5613 assert dt.tzinfo is self
5614
5615 # Find first Sunday in April.
5616 start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))
5617 assert start.weekday() == 6 and start.month == 4 and start.day <= 7
5618
5619 # Find last Sunday in October.
5620 end = first_sunday_on_or_after(DSTEND.replace(year=dt.year))
5621 assert end.weekday() == 6 and end.month == 10 and end.day >= 25
5622
5623 # Can't compare naive to aware objects, so strip the timezone from
5624 # dt first.
5625 if start <= dt.replace(tzinfo=None) < end:
5626 return HOUR
5627 else:
5628 return ZERO
5629
5630 Eastern = USTimeZone(-5, "Eastern", "EST", "EDT")
5631 Central = USTimeZone(-6, "Central", "CST", "CDT")
5632 Mountain = USTimeZone(-7, "Mountain", "MST", "MDT")
5633 Pacific = USTimeZone(-8, "Pacific", "PST", "PDT")
5634 utc_real = FixedOffset(0, "UTC", 0)
5635 # For better test coverage, we want another flavor of UTC that's west of
5636 # the Eastern and Pacific timezones.
5637 utc_fake = FixedOffset(-12*60, "UTCfake", 0)
5638
5639 class TestTimezoneConversions(unittest.TestCase):
5640 # The DST switch times for 2002, in std time.
5641 dston = datetime(2002, 4, 7, 2)
5642 dstoff = datetime(2002, 10, 27, 1)
5643
5644 theclass = datetime
5645
5646 # Check a time that's inside DST.
5647 def checkinside(self, dt, tz, utc, dston, dstoff):
5648 self.assertEqual(dt.dst(), HOUR)
5649
5650 # Conversion to our own timezone is always an identity.
5651 self.assertEqual(dt.astimezone(tz), dt)
5652
5653 asutc = dt.astimezone(utc)
5654 there_and_back = asutc.astimezone(tz)
5655
5656 # Conversion to UTC and back isn't always an identity here,
5657 # because there are redundant spellings (in local time) of
5658 # UTC time when DST begins: the clock jumps from 1:59:59
5659 # to 3:00:00, and a local time of 2:MM:SS doesn't really
5660 # make sense then. The classes above treat 2:MM:SS as
5661 # daylight time then (it's "after 2am"), really an alias
5662 # for 1:MM:SS standard time. The latter form is what
5663 # conversion back from UTC produces.
5664 if dt.date() == dston.date() and dt.hour == 2:
5665 # We're in the redundant hour, and coming back from
5666 # UTC gives the 1:MM:SS standard-time spelling.
5667 self.assertEqual(there_and_back + HOUR, dt)
5668 # Although during was considered to be in daylight
5669 # time, there_and_back is not.
5670 self.assertEqual(there_and_back.dst(), ZERO)
5671 # They're the same times in UTC.
5672 self.assertEqual(there_and_back.astimezone(utc),
5673 dt.astimezone(utc))
5674 else:
5675 # We're not in the redundant hour.
5676 self.assertEqual(dt, there_and_back)
5677
5678 # Because we have a redundant spelling when DST begins, there is
5679 # (unfortunately) an hour when DST ends that can't be spelled at all in
5680 # local time. When DST ends, the clock jumps from 1:59 back to 1:00
5681 # again. The hour 1:MM DST has no spelling then: 1:MM is taken to be
5682 # standard time. 1:MM DST == 0:MM EST, but 0:MM is taken to be
5683 # daylight time. The hour 1:MM daylight == 0:MM standard can't be
5684 # expressed in local time. Nevertheless, we want conversion back
5685 # from UTC to mimic the local clock's "repeat an hour" behavior.
5686 nexthour_utc = asutc + HOUR
5687 nexthour_tz = nexthour_utc.astimezone(tz)
5688 if dt.date() == dstoff.date() and dt.hour == 0:
5689 # We're in the hour before the last DST hour. The last DST hour
5690 # is ineffable. We want the conversion back to repeat 1:MM.
5691 self.assertEqual(nexthour_tz, dt.replace(hour=1))
5692 nexthour_utc += HOUR
5693 nexthour_tz = nexthour_utc.astimezone(tz)
5694 self.assertEqual(nexthour_tz, dt.replace(hour=1))
5695 else:
5696 self.assertEqual(nexthour_tz - dt, HOUR)
5697
5698 # Check a time that's outside DST.
5699 def checkoutside(self, dt, tz, utc):
5700 self.assertEqual(dt.dst(), ZERO)
5701
5702 # Conversion to our own timezone is always an identity.
5703 self.assertEqual(dt.astimezone(tz), dt)
5704
5705 # Converting to UTC and back is an identity too.
5706 asutc = dt.astimezone(utc)
5707 there_and_back = asutc.astimezone(tz)
5708 self.assertEqual(dt, there_and_back)
5709
5710 def convert_between_tz_and_utc(self, tz, utc):
5711 dston = self.dston.replace(tzinfo=tz)
5712 # Because 1:MM on the day DST ends is taken as being standard time,
5713 # there is no spelling in tz for the last hour of daylight time.
5714 # For purposes of the test, the last hour of DST is 0:MM, which is
5715 # taken as being daylight time (and 1:MM is taken as being standard
5716 # time).
5717 dstoff = self.dstoff.replace(tzinfo=tz)
5718 for delta in (timedelta(weeks=13),
5719 DAY,
5720 HOUR,
5721 timedelta(minutes=1),
5722 timedelta(microseconds=1)):
5723
5724 self.checkinside(dston, tz, utc, dston, dstoff)
5725 for during in dston + delta, dstoff - delta:
5726 self.checkinside(during, tz, utc, dston, dstoff)
5727
5728 self.checkoutside(dstoff, tz, utc)
5729 for outside in dston - delta, dstoff + delta:
5730 self.checkoutside(outside, tz, utc)
5731
5732 def test_easy(self):
5733 # Despite the name of this test, the endcases are excruciating.
5734 self.convert_between_tz_and_utc(Eastern, utc_real)
5735 self.convert_between_tz_and_utc(Pacific, utc_real)
5736 self.convert_between_tz_and_utc(Eastern, utc_fake)
5737 self.convert_between_tz_and_utc(Pacific, utc_fake)
5738 # The next is really dancing near the edge. It works because
5739 # Pacific and Eastern are far enough apart that their "problem
5740 # hours" don't overlap.
5741 self.convert_between_tz_and_utc(Eastern, Pacific)
5742 self.convert_between_tz_and_utc(Pacific, Eastern)
5743 # OTOH, these fail! Don't enable them. The difficulty is that
5744 # the edge case tests assume that every hour is representable in
5745 # the "utc" class. This is always true for a fixed-offset tzinfo
5746 # class (like utc_real and utc_fake), but not for Eastern or Central.
5747 # For these adjacent DST-aware time zones, the range of time offsets
5748 # tested ends up creating hours in the one that aren't representable
5749 # in the other. For the same reason, we would see failures in the
5750 # Eastern vs Pacific tests too if we added 3*HOUR to the list of
5751 # offset deltas in convert_between_tz_and_utc().
5752 #
5753 # self.convert_between_tz_and_utc(Eastern, Central) # can't work
5754 # self.convert_between_tz_and_utc(Central, Eastern) # can't work
5755
5756 def test_tricky(self):
5757 # 22:00 on day before daylight starts.
5758 fourback = self.dston - timedelta(hours=4)
5759 ninewest = FixedOffset(-9*60, "-0900", 0)
5760 fourback = fourback.replace(tzinfo=ninewest)
5761 # 22:00-0900 is 7:00 UTC == 2:00 EST == 3:00 DST. Since it's "after
5762 # 2", we should get the 3 spelling.
5763 # If we plug 22:00 the day before into Eastern, it "looks like std
5764 # time", so its offset is returned as -5, and -5 - -9 = 4. Adding 4
5765 # to 22:00 lands on 2:00, which makes no sense in local time (the
5766 # local clock jumps from 1 to 3). The point here is to make sure we
5767 # get the 3 spelling.
5768 expected = self.dston.replace(hour=3)
5769 got = fourback.astimezone(Eastern).replace(tzinfo=None)
5770 self.assertEqual(expected, got)
5771
5772 # Similar, but map to 6:00 UTC == 1:00 EST == 2:00 DST. In that
5773 # case we want the 1:00 spelling.
5774 sixutc = self.dston.replace(hour=6, tzinfo=utc_real)
5775 # Now 6:00 "looks like daylight", so the offset wrt Eastern is -4,
5776 # and adding -4-0 == -4 gives the 2:00 spelling. We want the 1:00 EST
5777 # spelling.
5778 expected = self.dston.replace(hour=1)
5779 got = sixutc.astimezone(Eastern).replace(tzinfo=None)
5780 self.assertEqual(expected, got)
5781
5782 # Now on the day DST ends, we want "repeat an hour" behavior.
5783 # UTC 4:MM 5:MM 6:MM 7:MM checking these
5784 # EST 23:MM 0:MM 1:MM 2:MM
5785 # EDT 0:MM 1:MM 2:MM 3:MM
5786 # wall 0:MM 1:MM 1:MM 2:MM against these
5787 for utc in utc_real, utc_fake:
5788 for tz in Eastern, Pacific:
5789 first_std_hour = self.dstoff - timedelta(hours=2) # 23:MM
5790 # Convert that to UTC.
5791 first_std_hour -= tz.utcoffset(None)
5792 # Adjust for possibly fake UTC.
5793 asutc = first_std_hour + utc.utcoffset(None)
5794 # First UTC hour to convert; this is 4:00 when utc=utc_real &
5795 # tz=Eastern.
5796 asutcbase = asutc.replace(tzinfo=utc)
5797 for tzhour in (0, 1, 1, 2):
5798 expectedbase = self.dstoff.replace(hour=tzhour)
5799 for minute in 0, 30, 59:
5800 expected = expectedbase.replace(minute=minute)
5801 asutc = asutcbase.replace(minute=minute)
5802 astz = asutc.astimezone(tz)
5803 self.assertEqual(astz.replace(tzinfo=None), expected)
5804 asutcbase += HOUR
5805
5806
5807 def test_bogus_dst(self):
5808 class ok(tzinfo):
5809 def utcoffset(self, dt): return HOUR
5810 def dst(self, dt): return HOUR
5811
5812 now = self.theclass.now().replace(tzinfo=utc_real)
5813 # Doesn't blow up.
5814 now.astimezone(ok())
5815
5816 # Does blow up.
5817 class notok(ok):
5818 def dst(self, dt): return None
5819 self.assertRaises(ValueError, now.astimezone, notok())
5820
5821 # Sometimes blow up. In the following, tzinfo.dst()
5822 # implementation may return None or not None depending on
5823 # whether DST is assumed to be in effect. In this situation,
5824 # a ValueError should be raised by astimezone().
5825 class tricky_notok(ok):
5826 def dst(self, dt):
5827 if dt.year == 2000:
5828 return None
5829 else:
5830 return 10*HOUR
5831 dt = self.theclass(2001, 1, 1).replace(tzinfo=utc_real)
5832 self.assertRaises(ValueError, dt.astimezone, tricky_notok())
5833
5834 def test_fromutc(self):
5835 self.assertRaises(TypeError, Eastern.fromutc) # not enough args
5836 now = datetime.now(tz=utc_real)
5837 self.assertRaises(ValueError, Eastern.fromutc, now) # wrong tzinfo
5838 now = now.replace(tzinfo=Eastern) # insert correct tzinfo
5839 enow = Eastern.fromutc(now) # doesn't blow up
5840 self.assertEqual(enow.tzinfo, Eastern) # has right tzinfo member
5841 self.assertRaises(TypeError, Eastern.fromutc, now, now) # too many args
5842 self.assertRaises(TypeError, Eastern.fromutc, date.today()) # wrong type
5843
5844 # Always converts UTC to standard time.
5845 class FauxUSTimeZone(USTimeZone):
5846 def fromutc(self, dt):
5847 return dt + self.stdoffset
5848 FEastern = FauxUSTimeZone(-5, "FEastern", "FEST", "FEDT")
5849
5850 # UTC 4:MM 5:MM 6:MM 7:MM 8:MM 9:MM
5851 # EST 23:MM 0:MM 1:MM 2:MM 3:MM 4:MM
5852 # EDT 0:MM 1:MM 2:MM 3:MM 4:MM 5:MM
5853
5854 # Check around DST start.
5855 start = self.dston.replace(hour=4, tzinfo=Eastern)
5856 fstart = start.replace(tzinfo=FEastern)
5857 for wall in 23, 0, 1, 3, 4, 5:
5858 expected = start.replace(hour=wall)
5859 if wall == 23:
5860 expected -= timedelta(days=1)
5861 got = Eastern.fromutc(start)
5862 self.assertEqual(expected, got)
5863
5864 expected = fstart + FEastern.stdoffset
5865 got = FEastern.fromutc(fstart)
5866 self.assertEqual(expected, got)
5867
5868 # Ensure astimezone() calls fromutc() too.
5869 got = fstart.replace(tzinfo=utc_real).astimezone(FEastern)
5870 self.assertEqual(expected, got)
5871
5872 start += HOUR
5873 fstart += HOUR
5874
5875 # Check around DST end.
5876 start = self.dstoff.replace(hour=4, tzinfo=Eastern)
5877 fstart = start.replace(tzinfo=FEastern)
5878 for wall in 0, 1, 1, 2, 3, 4:
5879 expected = start.replace(hour=wall)
5880 got = Eastern.fromutc(start)
5881 self.assertEqual(expected, got)
5882
5883 expected = fstart + FEastern.stdoffset
5884 got = FEastern.fromutc(fstart)
5885 self.assertEqual(expected, got)
5886
5887 # Ensure astimezone() calls fromutc() too.
5888 got = fstart.replace(tzinfo=utc_real).astimezone(FEastern)
5889 self.assertEqual(expected, got)
5890
5891 start += HOUR
5892 fstart += HOUR
5893
5894
5895 #############################################################################
5896 # oddballs
5897
5898 class Oddballs(unittest.TestCase):
5899
5900 def test_date_datetime_comparison(self):
5901 # bpo-1028306, bpo-5516 (gh-49766)
5902 # Trying to compare a date to a datetime should act like a mixed-
5903 # type comparison, despite that datetime is a subclass of date.
5904 as_date = date.today()
5905 as_datetime = datetime.combine(as_date, time())
5906 date_sc = SubclassDate(as_date.year, as_date.month, as_date.day)
5907 datetime_sc = SubclassDatetime(as_date.year, as_date.month,
5908 as_date.day, 0, 0, 0)
5909 for d in (as_date, date_sc):
5910 for dt in (as_datetime, datetime_sc):
5911 for x, y in (d, dt), (dt, d):
5912 self.assertTrue(x != y)
5913 self.assertFalse(x == y)
5914 self.assertRaises(TypeError, lambda: x < y)
5915 self.assertRaises(TypeError, lambda: x <= y)
5916 self.assertRaises(TypeError, lambda: x > y)
5917 self.assertRaises(TypeError, lambda: x >= y)
5918
5919 # And date should compare with other subclasses of date. If a
5920 # subclass wants to stop this, it's up to the subclass to do so.
5921 # Ditto for datetimes.
5922 for x, y in ((as_date, date_sc),
5923 (date_sc, as_date),
5924 (as_datetime, datetime_sc),
5925 (datetime_sc, as_datetime)):
5926 self.assertTrue(x == y)
5927 self.assertFalse(x != y)
5928 self.assertFalse(x < y)
5929 self.assertFalse(x > y)
5930 self.assertTrue(x <= y)
5931 self.assertTrue(x >= y)
5932
5933 # Nevertheless, comparison should work if other object is an instance
5934 # of date or datetime class with overridden comparison operators.
5935 # So special methods should return NotImplemented, as if
5936 # date and datetime were independent classes.
5937 for x, y in (as_date, as_datetime), (as_datetime, as_date):
5938 self.assertEqual(x.__eq__(y), NotImplemented)
5939 self.assertEqual(x.__ne__(y), NotImplemented)
5940 self.assertEqual(x.__lt__(y), NotImplemented)
5941 self.assertEqual(x.__gt__(y), NotImplemented)
5942 self.assertEqual(x.__gt__(y), NotImplemented)
5943 self.assertEqual(x.__ge__(y), NotImplemented)
5944
5945 def test_extra_attributes(self):
5946 with self.assertWarns(DeprecationWarning):
5947 utcnow = datetime.utcnow()
5948 for x in [date.today(),
5949 time(),
5950 utcnow,
5951 timedelta(),
5952 tzinfo(),
5953 timezone(timedelta())]:
5954 with self.assertRaises(AttributeError):
5955 x.abc = 1
5956
5957 def test_check_arg_types(self):
5958 class Number:
5959 def __init__(self, value):
5960 self.value = value
5961 def __int__(self):
5962 return self.value
5963
5964 class Float(float):
5965 pass
5966
5967 for xx in [10.0, Float(10.9),
5968 decimal.Decimal(10), decimal.Decimal('10.9'),
5969 Number(10), Number(10.9),
5970 '10']:
5971 self.assertRaises(TypeError, datetime, xx, 10, 10, 10, 10, 10, 10)
5972 self.assertRaises(TypeError, datetime, 10, xx, 10, 10, 10, 10, 10)
5973 self.assertRaises(TypeError, datetime, 10, 10, xx, 10, 10, 10, 10)
5974 self.assertRaises(TypeError, datetime, 10, 10, 10, xx, 10, 10, 10)
5975 self.assertRaises(TypeError, datetime, 10, 10, 10, 10, xx, 10, 10)
5976 self.assertRaises(TypeError, datetime, 10, 10, 10, 10, 10, xx, 10)
5977 self.assertRaises(TypeError, datetime, 10, 10, 10, 10, 10, 10, xx)
5978
5979
5980 #############################################################################
5981 # Local Time Disambiguation
5982
5983 # An experimental reimplementation of fromutc that respects the "fold" flag.
5984
5985 class tzinfo2(tzinfo):
5986
5987 def fromutc(self, dt):
5988 "datetime in UTC -> datetime in local time."
5989
5990 if not isinstance(dt, datetime):
5991 raise TypeError("fromutc() requires a datetime argument")
5992 if dt.tzinfo is not self:
5993 raise ValueError("dt.tzinfo is not self")
5994 # Returned value satisfies
5995 # dt + ldt.utcoffset() = ldt
5996 off0 = dt.replace(fold=0).utcoffset()
5997 off1 = dt.replace(fold=1).utcoffset()
5998 if off0 is None or off1 is None or dt.dst() is None:
5999 raise ValueError
6000 if off0 == off1:
6001 ldt = dt + off0
6002 off1 = ldt.utcoffset()
6003 if off0 == off1:
6004 return ldt
6005 # Now, we discovered both possible offsets, so
6006 # we can just try four possible solutions:
6007 for off in [off0, off1]:
6008 ldt = dt + off
6009 if ldt.utcoffset() == off:
6010 return ldt
6011 ldt = ldt.replace(fold=1)
6012 if ldt.utcoffset() == off:
6013 return ldt
6014
6015 raise ValueError("No suitable local time found")
6016
6017 # Reimplementing simplified US timezones to respect the "fold" flag:
6018
6019 class USTimeZone2(tzinfo2):
6020
6021 def __init__(self, hours, reprname, stdname, dstname):
6022 self.stdoffset = timedelta(hours=hours)
6023 self.reprname = reprname
6024 self.stdname = stdname
6025 self.dstname = dstname
6026
6027 def __repr__(self):
6028 return self.reprname
6029
6030 def tzname(self, dt):
6031 if self.dst(dt):
6032 return self.dstname
6033 else:
6034 return self.stdname
6035
6036 def utcoffset(self, dt):
6037 return self.stdoffset + self.dst(dt)
6038
6039 def dst(self, dt):
6040 if dt is None or dt.tzinfo is None:
6041 # An exception instead may be sensible here, in one or more of
6042 # the cases.
6043 return ZERO
6044 assert dt.tzinfo is self
6045
6046 # Find first Sunday in April.
6047 start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))
6048 assert start.weekday() == 6 and start.month == 4 and start.day <= 7
6049
6050 # Find last Sunday in October.
6051 end = first_sunday_on_or_after(DSTEND.replace(year=dt.year))
6052 assert end.weekday() == 6 and end.month == 10 and end.day >= 25
6053
6054 # Can't compare naive to aware objects, so strip the timezone from
6055 # dt first.
6056 dt = dt.replace(tzinfo=None)
6057 if start + HOUR <= dt < end:
6058 # DST is in effect.
6059 return HOUR
6060 elif end <= dt < end + HOUR:
6061 # Fold (an ambiguous hour): use dt.fold to disambiguate.
6062 return ZERO if dt.fold else HOUR
6063 elif start <= dt < start + HOUR:
6064 # Gap (a non-existent hour): reverse the fold rule.
6065 return HOUR if dt.fold else ZERO
6066 else:
6067 # DST is off.
6068 return ZERO
6069
6070 Eastern2 = USTimeZone2(-5, "Eastern2", "EST", "EDT")
6071 Central2 = USTimeZone2(-6, "Central2", "CST", "CDT")
6072 Mountain2 = USTimeZone2(-7, "Mountain2", "MST", "MDT")
6073 Pacific2 = USTimeZone2(-8, "Pacific2", "PST", "PDT")
6074
6075 # Europe_Vilnius_1941 tzinfo implementation reproduces the following
6076 # 1941 transition from Olson's tzdist:
6077 #
6078 # Zone NAME GMTOFF RULES FORMAT [UNTIL]
6079 # ZoneEurope/Vilnius 1:00 - CET 1940 Aug 3
6080 # 3:00 - MSK 1941 Jun 24
6081 # 1:00 C-Eur CE%sT 1944 Aug
6082 #
6083 # $ zdump -v Europe/Vilnius | grep 1941
6084 # Europe/Vilnius Mon Jun 23 20:59:59 1941 UTC = Mon Jun 23 23:59:59 1941 MSK isdst=0 gmtoff=10800
6085 # Europe/Vilnius Mon Jun 23 21:00:00 1941 UTC = Mon Jun 23 23:00:00 1941 CEST isdst=1 gmtoff=7200
6086
6087 class Europe_Vilnius_1941(tzinfo):
6088 def _utc_fold(self):
6089 return [datetime(1941, 6, 23, 21, tzinfo=self), # Mon Jun 23 21:00:00 1941 UTC
6090 datetime(1941, 6, 23, 22, tzinfo=self)] # Mon Jun 23 22:00:00 1941 UTC
6091
6092 def _loc_fold(self):
6093 return [datetime(1941, 6, 23, 23, tzinfo=self), # Mon Jun 23 23:00:00 1941 MSK / CEST
6094 datetime(1941, 6, 24, 0, tzinfo=self)] # Mon Jun 24 00:00:00 1941 CEST
6095
6096 def utcoffset(self, dt):
6097 fold_start, fold_stop = self._loc_fold()
6098 if dt < fold_start:
6099 return 3 * HOUR
6100 if dt < fold_stop:
6101 return (2 if dt.fold else 3) * HOUR
6102 # if dt >= fold_stop
6103 return 2 * HOUR
6104
6105 def dst(self, dt):
6106 fold_start, fold_stop = self._loc_fold()
6107 if dt < fold_start:
6108 return 0 * HOUR
6109 if dt < fold_stop:
6110 return (1 if dt.fold else 0) * HOUR
6111 # if dt >= fold_stop
6112 return 1 * HOUR
6113
6114 def tzname(self, dt):
6115 fold_start, fold_stop = self._loc_fold()
6116 if dt < fold_start:
6117 return 'MSK'
6118 if dt < fold_stop:
6119 return ('MSK', 'CEST')[dt.fold]
6120 # if dt >= fold_stop
6121 return 'CEST'
6122
6123 def fromutc(self, dt):
6124 assert dt.fold == 0
6125 assert dt.tzinfo is self
6126 if dt.year != 1941:
6127 raise NotImplementedError
6128 fold_start, fold_stop = self._utc_fold()
6129 if dt < fold_start:
6130 return dt + 3 * HOUR
6131 if dt < fold_stop:
6132 return (dt + 2 * HOUR).replace(fold=1)
6133 # if dt >= fold_stop
6134 return dt + 2 * HOUR
6135
6136
6137 class TestLocalTimeDisambiguation(unittest.TestCase):
6138
6139 def test_vilnius_1941_fromutc(self):
6140 Vilnius = Europe_Vilnius_1941()
6141
6142 gdt = datetime(1941, 6, 23, 20, 59, 59, tzinfo=timezone.utc)
6143 ldt = gdt.astimezone(Vilnius)
6144 self.assertEqual(ldt.strftime("%a %b %d %H:%M:%S %Y %Z%z"),
6145 'Mon Jun 23 23:59:59 1941 MSK+0300')
6146 self.assertEqual(ldt.fold, 0)
6147 self.assertFalse(ldt.dst())
6148
6149 gdt = datetime(1941, 6, 23, 21, tzinfo=timezone.utc)
6150 ldt = gdt.astimezone(Vilnius)
6151 self.assertEqual(ldt.strftime("%a %b %d %H:%M:%S %Y %Z%z"),
6152 'Mon Jun 23 23:00:00 1941 CEST+0200')
6153 self.assertEqual(ldt.fold, 1)
6154 self.assertTrue(ldt.dst())
6155
6156 gdt = datetime(1941, 6, 23, 22, tzinfo=timezone.utc)
6157 ldt = gdt.astimezone(Vilnius)
6158 self.assertEqual(ldt.strftime("%a %b %d %H:%M:%S %Y %Z%z"),
6159 'Tue Jun 24 00:00:00 1941 CEST+0200')
6160 self.assertEqual(ldt.fold, 0)
6161 self.assertTrue(ldt.dst())
6162
6163 def test_vilnius_1941_toutc(self):
6164 Vilnius = Europe_Vilnius_1941()
6165
6166 ldt = datetime(1941, 6, 23, 22, 59, 59, tzinfo=Vilnius)
6167 gdt = ldt.astimezone(timezone.utc)
6168 self.assertEqual(gdt.strftime("%a %b %d %H:%M:%S %Y %Z"),
6169 'Mon Jun 23 19:59:59 1941 UTC')
6170
6171 ldt = datetime(1941, 6, 23, 23, 59, 59, tzinfo=Vilnius)
6172 gdt = ldt.astimezone(timezone.utc)
6173 self.assertEqual(gdt.strftime("%a %b %d %H:%M:%S %Y %Z"),
6174 'Mon Jun 23 20:59:59 1941 UTC')
6175
6176 ldt = datetime(1941, 6, 23, 23, 59, 59, tzinfo=Vilnius, fold=1)
6177 gdt = ldt.astimezone(timezone.utc)
6178 self.assertEqual(gdt.strftime("%a %b %d %H:%M:%S %Y %Z"),
6179 'Mon Jun 23 21:59:59 1941 UTC')
6180
6181 ldt = datetime(1941, 6, 24, 0, tzinfo=Vilnius)
6182 gdt = ldt.astimezone(timezone.utc)
6183 self.assertEqual(gdt.strftime("%a %b %d %H:%M:%S %Y %Z"),
6184 'Mon Jun 23 22:00:00 1941 UTC')
6185
6186 def test_constructors(self):
6187 t = time(0, fold=1)
6188 dt = datetime(1, 1, 1, fold=1)
6189 self.assertEqual(t.fold, 1)
6190 self.assertEqual(dt.fold, 1)
6191 with self.assertRaises(TypeError):
6192 time(0, 0, 0, 0, None, 0)
6193
6194 def test_member(self):
6195 dt = datetime(1, 1, 1, fold=1)
6196 t = dt.time()
6197 self.assertEqual(t.fold, 1)
6198 t = dt.timetz()
6199 self.assertEqual(t.fold, 1)
6200
6201 def test_replace(self):
6202 t = time(0)
6203 dt = datetime(1, 1, 1)
6204 self.assertEqual(t.replace(fold=1).fold, 1)
6205 self.assertEqual(dt.replace(fold=1).fold, 1)
6206 self.assertEqual(t.replace(fold=0).fold, 0)
6207 self.assertEqual(dt.replace(fold=0).fold, 0)
6208 # Check that replacement of other fields does not change "fold".
6209 t = t.replace(fold=1, tzinfo=Eastern)
6210 dt = dt.replace(fold=1, tzinfo=Eastern)
6211 self.assertEqual(t.replace(tzinfo=None).fold, 1)
6212 self.assertEqual(dt.replace(tzinfo=None).fold, 1)
6213 # Out of bounds.
6214 with self.assertRaises(ValueError):
6215 t.replace(fold=2)
6216 with self.assertRaises(ValueError):
6217 dt.replace(fold=2)
6218 # Check that fold is a keyword-only argument
6219 with self.assertRaises(TypeError):
6220 t.replace(1, 1, 1, None, 1)
6221 with self.assertRaises(TypeError):
6222 dt.replace(1, 1, 1, 1, 1, 1, 1, None, 1)
6223
6224 def test_comparison(self):
6225 t = time(0)
6226 dt = datetime(1, 1, 1)
6227 self.assertEqual(t, t.replace(fold=1))
6228 self.assertEqual(dt, dt.replace(fold=1))
6229
6230 def test_hash(self):
6231 t = time(0)
6232 dt = datetime(1, 1, 1)
6233 self.assertEqual(hash(t), hash(t.replace(fold=1)))
6234 self.assertEqual(hash(dt), hash(dt.replace(fold=1)))
6235
6236 @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0')
6237 def test_fromtimestamp(self):
6238 s = 1414906200
6239 dt0 = datetime.fromtimestamp(s)
6240 dt1 = datetime.fromtimestamp(s + 3600)
6241 self.assertEqual(dt0.fold, 0)
6242 self.assertEqual(dt1.fold, 1)
6243
6244 @support.run_with_tz('Australia/Lord_Howe')
6245 def test_fromtimestamp_lord_howe(self):
6246 tm = _time.localtime(1.4e9)
6247 if _time.strftime('%Z%z', tm) != 'LHST+1030':
6248 self.skipTest('Australia/Lord_Howe timezone is not supported on this platform')
6249 # $ TZ=Australia/Lord_Howe date -r 1428158700
6250 # Sun Apr 5 01:45:00 LHDT 2015
6251 # $ TZ=Australia/Lord_Howe date -r 1428160500
6252 # Sun Apr 5 01:45:00 LHST 2015
6253 s = 1428158700
6254 t0 = datetime.fromtimestamp(s)
6255 t1 = datetime.fromtimestamp(s + 1800)
6256 self.assertEqual(t0, t1)
6257 self.assertEqual(t0.fold, 0)
6258 self.assertEqual(t1.fold, 1)
6259
6260 def test_fromtimestamp_low_fold_detection(self):
6261 # Ensure that fold detection doesn't cause an
6262 # OSError for really low values, see bpo-29097
6263 self.assertEqual(datetime.fromtimestamp(0).fold, 0)
6264
6265 @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0')
6266 def test_timestamp(self):
6267 dt0 = datetime(2014, 11, 2, 1, 30)
6268 dt1 = dt0.replace(fold=1)
6269 self.assertEqual(dt0.timestamp() + 3600,
6270 dt1.timestamp())
6271
6272 @support.run_with_tz('Australia/Lord_Howe')
6273 def test_timestamp_lord_howe(self):
6274 tm = _time.localtime(1.4e9)
6275 if _time.strftime('%Z%z', tm) != 'LHST+1030':
6276 self.skipTest('Australia/Lord_Howe timezone is not supported on this platform')
6277 t = datetime(2015, 4, 5, 1, 45)
6278 s0 = t.replace(fold=0).timestamp()
6279 s1 = t.replace(fold=1).timestamp()
6280 self.assertEqual(s0 + 1800, s1)
6281
6282 @support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0')
6283 def test_astimezone(self):
6284 dt0 = datetime(2014, 11, 2, 1, 30)
6285 dt1 = dt0.replace(fold=1)
6286 # Convert both naive instances to aware.
6287 adt0 = dt0.astimezone()
6288 adt1 = dt1.astimezone()
6289 # Check that the first instance in DST zone and the second in STD
6290 self.assertEqual(adt0.tzname(), 'EDT')
6291 self.assertEqual(adt1.tzname(), 'EST')
6292 self.assertEqual(adt0 + HOUR, adt1)
6293 # Aware instances with fixed offset tzinfo's always have fold=0
6294 self.assertEqual(adt0.fold, 0)
6295 self.assertEqual(adt1.fold, 0)
6296
6297 def test_pickle_fold(self):
6298 t = time(fold=1)
6299 dt = datetime(1, 1, 1, fold=1)
6300 for pickler, unpickler, proto in pickle_choices:
6301 for x in [t, dt]:
6302 s = pickler.dumps(x, proto)
6303 y = unpickler.loads(s)
6304 self.assertEqual(x, y)
6305 self.assertEqual((0 if proto < 4 else x.fold), y.fold)
6306
6307 def test_repr(self):
6308 t = time(fold=1)
6309 dt = datetime(1, 1, 1, fold=1)
6310 self.assertEqual(repr(t), 'datetime.time(0, 0, fold=1)')
6311 self.assertEqual(repr(dt),
6312 'datetime.datetime(1, 1, 1, 0, 0, fold=1)')
6313
6314 def test_dst(self):
6315 # Let's first establish that things work in regular times.
6316 dt_summer = datetime(2002, 10, 27, 1, tzinfo=Eastern2) - timedelta.resolution
6317 dt_winter = datetime(2002, 10, 27, 2, tzinfo=Eastern2)
6318 self.assertEqual(dt_summer.dst(), HOUR)
6319 self.assertEqual(dt_winter.dst(), ZERO)
6320 # The disambiguation flag is ignored
6321 self.assertEqual(dt_summer.replace(fold=1).dst(), HOUR)
6322 self.assertEqual(dt_winter.replace(fold=1).dst(), ZERO)
6323
6324 # Pick local time in the fold.
6325 for minute in [0, 30, 59]:
6326 dt = datetime(2002, 10, 27, 1, minute, tzinfo=Eastern2)
6327 # With fold=0 (the default) it is in DST.
6328 self.assertEqual(dt.dst(), HOUR)
6329 # With fold=1 it is in STD.
6330 self.assertEqual(dt.replace(fold=1).dst(), ZERO)
6331
6332 # Pick local time in the gap.
6333 for minute in [0, 30, 59]:
6334 dt = datetime(2002, 4, 7, 2, minute, tzinfo=Eastern2)
6335 # With fold=0 (the default) it is in STD.
6336 self.assertEqual(dt.dst(), ZERO)
6337 # With fold=1 it is in DST.
6338 self.assertEqual(dt.replace(fold=1).dst(), HOUR)
6339
6340
6341 def test_utcoffset(self):
6342 # Let's first establish that things work in regular times.
6343 dt_summer = datetime(2002, 10, 27, 1, tzinfo=Eastern2) - timedelta.resolution
6344 dt_winter = datetime(2002, 10, 27, 2, tzinfo=Eastern2)
6345 self.assertEqual(dt_summer.utcoffset(), -4 * HOUR)
6346 self.assertEqual(dt_winter.utcoffset(), -5 * HOUR)
6347 # The disambiguation flag is ignored
6348 self.assertEqual(dt_summer.replace(fold=1).utcoffset(), -4 * HOUR)
6349 self.assertEqual(dt_winter.replace(fold=1).utcoffset(), -5 * HOUR)
6350
6351 def test_fromutc(self):
6352 # Let's first establish that things work in regular times.
6353 u_summer = datetime(2002, 10, 27, 6, tzinfo=Eastern2) - timedelta.resolution
6354 u_winter = datetime(2002, 10, 27, 7, tzinfo=Eastern2)
6355 t_summer = Eastern2.fromutc(u_summer)
6356 t_winter = Eastern2.fromutc(u_winter)
6357 self.assertEqual(t_summer, u_summer - 4 * HOUR)
6358 self.assertEqual(t_winter, u_winter - 5 * HOUR)
6359 self.assertEqual(t_summer.fold, 0)
6360 self.assertEqual(t_winter.fold, 0)
6361
6362 # What happens in the fall-back fold?
6363 u = datetime(2002, 10, 27, 5, 30, tzinfo=Eastern2)
6364 t0 = Eastern2.fromutc(u)
6365 u += HOUR
6366 t1 = Eastern2.fromutc(u)
6367 self.assertEqual(t0, t1)
6368 self.assertEqual(t0.fold, 0)
6369 self.assertEqual(t1.fold, 1)
6370 # The tricky part is when u is in the local fold:
6371 u = datetime(2002, 10, 27, 1, 30, tzinfo=Eastern2)
6372 t = Eastern2.fromutc(u)
6373 self.assertEqual((t.day, t.hour), (26, 21))
6374 # .. or gets into the local fold after a standard time adjustment
6375 u = datetime(2002, 10, 27, 6, 30, tzinfo=Eastern2)
6376 t = Eastern2.fromutc(u)
6377 self.assertEqual((t.day, t.hour), (27, 1))
6378
6379 # What happens in the spring-forward gap?
6380 u = datetime(2002, 4, 7, 2, 0, tzinfo=Eastern2)
6381 t = Eastern2.fromutc(u)
6382 self.assertEqual((t.day, t.hour), (6, 21))
6383
6384 def test_mixed_compare_regular(self):
6385 t = datetime(2000, 1, 1, tzinfo=Eastern2)
6386 self.assertEqual(t, t.astimezone(timezone.utc))
6387 t = datetime(2000, 6, 1, tzinfo=Eastern2)
6388 self.assertEqual(t, t.astimezone(timezone.utc))
6389
6390 def test_mixed_compare_fold(self):
6391 t_fold = datetime(2002, 10, 27, 1, 45, tzinfo=Eastern2)
6392 t_fold_utc = t_fold.astimezone(timezone.utc)
6393 self.assertNotEqual(t_fold, t_fold_utc)
6394 self.assertNotEqual(t_fold_utc, t_fold)
6395
6396 def test_mixed_compare_gap(self):
6397 t_gap = datetime(2002, 4, 7, 2, 45, tzinfo=Eastern2)
6398 t_gap_utc = t_gap.astimezone(timezone.utc)
6399 self.assertNotEqual(t_gap, t_gap_utc)
6400 self.assertNotEqual(t_gap_utc, t_gap)
6401
6402 def test_hash_aware(self):
6403 t = datetime(2000, 1, 1, tzinfo=Eastern2)
6404 self.assertEqual(hash(t), hash(t.replace(fold=1)))
6405 t_fold = datetime(2002, 10, 27, 1, 45, tzinfo=Eastern2)
6406 t_gap = datetime(2002, 4, 7, 2, 45, tzinfo=Eastern2)
6407 self.assertEqual(hash(t_fold), hash(t_fold.replace(fold=1)))
6408 self.assertEqual(hash(t_gap), hash(t_gap.replace(fold=1)))
6409
6410 SEC = timedelta(0, 1)
6411
6412 def pairs(iterable):
6413 a, b = itertools.tee(iterable)
6414 next(b, None)
6415 return zip(a, b)
6416
6417 class ZoneInfo(tzinfo):
6418 zoneroot = '/usr/share/zoneinfo'
6419 def __init__(self, ut, ti):
6420 """
6421
6422 :param ut: array
6423 Array of transition point timestamps
6424 :param ti: list
6425 A list of (offset, isdst, abbr) tuples
6426 :return: None
6427 """
6428 self.ut = ut
6429 self.ti = ti
6430 self.lt = self.invert(ut, ti)
6431
6432 @staticmethod
6433 def invert(ut, ti):
6434 lt = (array('q', ut), array('q', ut))
6435 if ut:
6436 offset = ti[0][0] // SEC
6437 lt[0][0] += offset
6438 lt[1][0] += offset
6439 for i in range(1, len(ut)):
6440 lt[0][i] += ti[i-1][0] // SEC
6441 lt[1][i] += ti[i][0] // SEC
6442 return lt
6443
6444 @classmethod
6445 def fromfile(cls, fileobj):
6446 if fileobj.read(4).decode() != "TZif":
6447 raise ValueError("not a zoneinfo file")
6448 fileobj.seek(32)
6449 counts = array('i')
6450 counts.fromfile(fileobj, 3)
6451 if sys.byteorder != 'big':
6452 counts.byteswap()
6453
6454 ut = array('i')
6455 ut.fromfile(fileobj, counts[0])
6456 if sys.byteorder != 'big':
6457 ut.byteswap()
6458
6459 type_indices = array('B')
6460 type_indices.fromfile(fileobj, counts[0])
6461
6462 ttis = []
6463 for i in range(counts[1]):
6464 ttis.append(struct.unpack(">lbb", fileobj.read(6)))
6465
6466 abbrs = fileobj.read(counts[2])
6467
6468 # Convert ttis
6469 for i, (gmtoff, isdst, abbrind) in enumerate(ttis):
6470 abbr = abbrs[abbrind:abbrs.find(0, abbrind)].decode()
6471 ttis[i] = (timedelta(0, gmtoff), isdst, abbr)
6472
6473 ti = [None] * len(ut)
6474 for i, idx in enumerate(type_indices):
6475 ti[i] = ttis[idx]
6476
6477 self = cls(ut, ti)
6478
6479 return self
6480
6481 @classmethod
6482 def fromname(cls, name):
6483 path = os.path.join(cls.zoneroot, name)
6484 with open(path, 'rb') as f:
6485 return cls.fromfile(f)
6486
6487 EPOCHORDINAL = date(1970, 1, 1).toordinal()
6488
6489 def fromutc(self, dt):
6490 """datetime in UTC -> datetime in local time."""
6491
6492 if not isinstance(dt, datetime):
6493 raise TypeError("fromutc() requires a datetime argument")
6494 if dt.tzinfo is not self:
6495 raise ValueError("dt.tzinfo is not self")
6496
6497 timestamp = ((dt.toordinal() - self.EPOCHORDINAL) * 86400
6498 + dt.hour * 3600
6499 + dt.minute * 60
6500 + dt.second)
6501
6502 if timestamp < self.ut[1]:
6503 tti = self.ti[0]
6504 fold = 0
6505 else:
6506 idx = bisect.bisect_right(self.ut, timestamp)
6507 assert self.ut[idx-1] <= timestamp
6508 assert idx == len(self.ut) or timestamp < self.ut[idx]
6509 tti_prev, tti = self.ti[idx-2:idx]
6510 # Detect fold
6511 shift = tti_prev[0] - tti[0]
6512 fold = (shift > timedelta(0, timestamp - self.ut[idx-1]))
6513 dt += tti[0]
6514 if fold:
6515 return dt.replace(fold=1)
6516 else:
6517 return dt
6518
6519 def _find_ti(self, dt, i):
6520 timestamp = ((dt.toordinal() - self.EPOCHORDINAL) * 86400
6521 + dt.hour * 3600
6522 + dt.minute * 60
6523 + dt.second)
6524 lt = self.lt[dt.fold]
6525 idx = bisect.bisect_right(lt, timestamp)
6526
6527 return self.ti[max(0, idx - 1)][i]
6528
6529 def utcoffset(self, dt):
6530 return self._find_ti(dt, 0)
6531
6532 def dst(self, dt):
6533 isdst = self._find_ti(dt, 1)
6534 # XXX: We cannot accurately determine the "save" value,
6535 # so let's return 1h whenever DST is in effect. Since
6536 # we don't use dst() in fromutc(), it is unlikely that
6537 # it will be needed for anything more than bool(dst()).
6538 return ZERO if isdst else HOUR
6539
6540 def tzname(self, dt):
6541 return self._find_ti(dt, 2)
6542
6543 @classmethod
6544 def zonenames(cls, zonedir=None):
6545 if zonedir is None:
6546 zonedir = cls.zoneroot
6547 zone_tab = os.path.join(zonedir, 'zone.tab')
6548 try:
6549 f = open(zone_tab)
6550 except OSError:
6551 return
6552 with f:
6553 for line in f:
6554 line = line.strip()
6555 if line and not line.startswith('#'):
6556 yield line.split()[2]
6557
6558 @classmethod
6559 def stats(cls, start_year=1):
6560 count = gap_count = fold_count = zeros_count = 0
6561 min_gap = min_fold = timedelta.max
6562 max_gap = max_fold = ZERO
6563 min_gap_datetime = max_gap_datetime = datetime.min
6564 min_gap_zone = max_gap_zone = None
6565 min_fold_datetime = max_fold_datetime = datetime.min
6566 min_fold_zone = max_fold_zone = None
6567 stats_since = datetime(start_year, 1, 1) # Starting from 1970 eliminates a lot of noise
6568 for zonename in cls.zonenames():
6569 count += 1
6570 tz = cls.fromname(zonename)
6571 for dt, shift in tz.transitions():
6572 if dt < stats_since:
6573 continue
6574 if shift > ZERO:
6575 gap_count += 1
6576 if (shift, dt) > (max_gap, max_gap_datetime):
6577 max_gap = shift
6578 max_gap_zone = zonename
6579 max_gap_datetime = dt
6580 if (shift, datetime.max - dt) < (min_gap, datetime.max - min_gap_datetime):
6581 min_gap = shift
6582 min_gap_zone = zonename
6583 min_gap_datetime = dt
6584 elif shift < ZERO:
6585 fold_count += 1
6586 shift = -shift
6587 if (shift, dt) > (max_fold, max_fold_datetime):
6588 max_fold = shift
6589 max_fold_zone = zonename
6590 max_fold_datetime = dt
6591 if (shift, datetime.max - dt) < (min_fold, datetime.max - min_fold_datetime):
6592 min_fold = shift
6593 min_fold_zone = zonename
6594 min_fold_datetime = dt
6595 else:
6596 zeros_count += 1
6597 trans_counts = (gap_count, fold_count, zeros_count)
6598 print("Number of zones: %5d" % count)
6599 print("Number of transitions: %5d = %d (gaps) + %d (folds) + %d (zeros)" %
6600 ((sum(trans_counts),) + trans_counts))
6601 print("Min gap: %16s at %s in %s" % (min_gap, min_gap_datetime, min_gap_zone))
6602 print("Max gap: %16s at %s in %s" % (max_gap, max_gap_datetime, max_gap_zone))
6603 print("Min fold: %16s at %s in %s" % (min_fold, min_fold_datetime, min_fold_zone))
6604 print("Max fold: %16s at %s in %s" % (max_fold, max_fold_datetime, max_fold_zone))
6605
6606
6607 def transitions(self):
6608 for (_, prev_ti), (t, ti) in pairs(zip(self.ut, self.ti)):
6609 shift = ti[0] - prev_ti[0]
6610 yield (EPOCH_NAIVE + timedelta(seconds=t)), shift
6611
6612 def nondst_folds(self):
6613 """Find all folds with the same value of isdst on both sides of the transition."""
6614 for (_, prev_ti), (t, ti) in pairs(zip(self.ut, self.ti)):
6615 shift = ti[0] - prev_ti[0]
6616 if shift < ZERO and ti[1] == prev_ti[1]:
6617 yield _utcfromtimestamp(datetime, t,), -shift, prev_ti[2], ti[2]
6618
6619 @classmethod
6620 def print_all_nondst_folds(cls, same_abbr=False, start_year=1):
6621 count = 0
6622 for zonename in cls.zonenames():
6623 tz = cls.fromname(zonename)
6624 for dt, shift, prev_abbr, abbr in tz.nondst_folds():
6625 if dt.year < start_year or same_abbr and prev_abbr != abbr:
6626 continue
6627 count += 1
6628 print("%3d) %-30s %s %10s %5s -> %s" %
6629 (count, zonename, dt, shift, prev_abbr, abbr))
6630
6631 def folds(self):
6632 for t, shift in self.transitions():
6633 if shift < ZERO:
6634 yield t, -shift
6635
6636 def gaps(self):
6637 for t, shift in self.transitions():
6638 if shift > ZERO:
6639 yield t, shift
6640
6641 def zeros(self):
6642 for t, shift in self.transitions():
6643 if not shift:
6644 yield t
6645
6646
6647 class ZoneInfoTest(unittest.TestCase):
6648 zonename = 'America/New_York'
6649
6650 def setUp(self):
6651 if sys.platform == "vxworks":
6652 self.skipTest("Skipping zoneinfo tests on VxWorks")
6653 if sys.platform == "win32":
6654 self.skipTest("Skipping zoneinfo tests on Windows")
6655 try:
6656 self.tz = ZoneInfo.fromname(self.zonename)
6657 except FileNotFoundError as err:
6658 self.skipTest("Skipping %s: %s" % (self.zonename, err))
6659
6660 def assertEquivDatetimes(self, a, b):
6661 self.assertEqual((a.replace(tzinfo=None), a.fold, id(a.tzinfo)),
6662 (b.replace(tzinfo=None), b.fold, id(b.tzinfo)))
6663
6664 def test_folds(self):
6665 tz = self.tz
6666 for dt, shift in tz.folds():
6667 for x in [0 * shift, 0.5 * shift, shift - timedelta.resolution]:
6668 udt = dt + x
6669 ldt = tz.fromutc(udt.replace(tzinfo=tz))
6670 self.assertEqual(ldt.fold, 1)
6671 adt = udt.replace(tzinfo=timezone.utc).astimezone(tz)
6672 self.assertEquivDatetimes(adt, ldt)
6673 utcoffset = ldt.utcoffset()
6674 self.assertEqual(ldt.replace(tzinfo=None), udt + utcoffset)
6675 # Round trip
6676 self.assertEquivDatetimes(ldt.astimezone(timezone.utc),
6677 udt.replace(tzinfo=timezone.utc))
6678
6679
6680 for x in [-timedelta.resolution, shift]:
6681 udt = dt + x
6682 udt = udt.replace(tzinfo=tz)
6683 ldt = tz.fromutc(udt)
6684 self.assertEqual(ldt.fold, 0)
6685
6686 def test_gaps(self):
6687 tz = self.tz
6688 for dt, shift in tz.gaps():
6689 for x in [0 * shift, 0.5 * shift, shift - timedelta.resolution]:
6690 udt = dt + x
6691 udt = udt.replace(tzinfo=tz)
6692 ldt = tz.fromutc(udt)
6693 self.assertEqual(ldt.fold, 0)
6694 adt = udt.replace(tzinfo=timezone.utc).astimezone(tz)
6695 self.assertEquivDatetimes(adt, ldt)
6696 utcoffset = ldt.utcoffset()
6697 self.assertEqual(ldt.replace(tzinfo=None), udt.replace(tzinfo=None) + utcoffset)
6698 # Create a local time inside the gap
6699 ldt = tz.fromutc(dt.replace(tzinfo=tz)) - shift + x
6700 self.assertLess(ldt.replace(fold=1).utcoffset(),
6701 ldt.replace(fold=0).utcoffset(),
6702 "At %s." % ldt)
6703
6704 for x in [-timedelta.resolution, shift]:
6705 udt = dt + x
6706 ldt = tz.fromutc(udt.replace(tzinfo=tz))
6707 self.assertEqual(ldt.fold, 0)
6708
6709 @classmethod
6710 @contextlib.contextmanager
6711 def _change_tz(cls, new_tzinfo):
6712 try:
6713 with os_helper.EnvironmentVarGuard() as env:
6714 env["TZ"] = new_tzinfo
6715 _time.tzset()
6716 yield
6717 finally:
6718 _time.tzset()
6719
6720 @unittest.skipUnless(
6721 hasattr(_time, "tzset"), "time module has no attribute tzset"
6722 )
6723 def test_system_transitions(self):
6724 if ('Riyadh8' in self.zonename or
6725 # From tzdata NEWS file:
6726 # The files solar87, solar88, and solar89 are no longer distributed.
6727 # They were a negative experiment - that is, a demonstration that
6728 # tz data can represent solar time only with some difficulty and error.
6729 # Their presence in the distribution caused confusion, as Riyadh
6730 # civil time was generally not solar time in those years.
6731 self.zonename.startswith('right/')):
6732 self.skipTest("Skipping %s" % self.zonename)
6733 tz = self.tz
6734 with self._change_tz(self.zonename):
6735 for udt, shift in tz.transitions():
6736 if udt.year >= 2037:
6737 # System support for times around the end of 32-bit time_t
6738 # and later is flaky on many systems.
6739 break
6740 s0 = (udt - datetime(1970, 1, 1)) // SEC
6741 ss = shift // SEC # shift seconds
6742 for x in [-40 * 3600, -20 * 3600, -1, 0,
6743 ss - 1, ss + 20 * 3600, ss + 40 * 3600]:
6744 s = s0 + x
6745 sdt = datetime.fromtimestamp(s)
6746 tzdt = datetime.fromtimestamp(s, tz).replace(tzinfo=None)
6747 self.assertEquivDatetimes(sdt, tzdt)
6748 s1 = sdt.timestamp()
6749 self.assertEqual(s, s1)
6750 if ss > 0: # gap
6751 # Create local time inside the gap
6752 dt = datetime.fromtimestamp(s0) - shift / 2
6753 ts0 = dt.timestamp()
6754 ts1 = dt.replace(fold=1).timestamp()
6755 self.assertEqual(ts0, s0 + ss / 2)
6756 self.assertEqual(ts1, s0 - ss / 2)
6757 # gh-83861
6758 utc0 = dt.astimezone(timezone.utc)
6759 utc1 = dt.replace(fold=1).astimezone(timezone.utc)
6760 self.assertEqual(utc0, utc1 + timedelta(0, ss))
6761
6762
6763 class ZoneInfoCompleteTest(unittest.TestSuite):
6764 def __init__(self):
6765 tests = []
6766 if is_resource_enabled('tzdata'):
6767 for name in ZoneInfo.zonenames():
6768 Test = type('ZoneInfoTest[%s]' % name, (ZoneInfoTest,), {})
6769 Test.zonename = name
6770 for method in dir(Test):
6771 if method.startswith('test_'):
6772 tests.append(Test(method))
6773 super().__init__(tests)
6774
6775 # Iran had a sub-minute UTC offset before 1946.
6776 class IranTest(ZoneInfoTest):
6777 zonename = 'Asia/Tehran'
6778
6779
6780 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
6781 class CapiTest(unittest.TestCase):
6782 def setUp(self):
6783 # Since the C API is not present in the _Pure tests, skip all tests
6784 if self.__class__.__name__.endswith('Pure'):
6785 self.skipTest('Not relevant in pure Python')
6786
6787 # This *must* be called, and it must be called first, so until either
6788 # restriction is loosened, we'll call it as part of test setup
6789 _testcapi.test_datetime_capi()
6790
6791 def test_utc_capi(self):
6792 for use_macro in (True, False):
6793 capi_utc = _testcapi.get_timezone_utc_capi(use_macro)
6794
6795 with self.subTest(use_macro=use_macro):
6796 self.assertIs(capi_utc, timezone.utc)
6797
6798 def test_timezones_capi(self):
6799 est_capi, est_macro, est_macro_nn = _testcapi.make_timezones_capi()
6800
6801 exp_named = timezone(timedelta(hours=-5), "EST")
6802 exp_unnamed = timezone(timedelta(hours=-5))
6803
6804 cases = [
6805 ('est_capi', est_capi, exp_named),
6806 ('est_macro', est_macro, exp_named),
6807 ('est_macro_nn', est_macro_nn, exp_unnamed)
6808 ]
6809
6810 for name, tz_act, tz_exp in cases:
6811 with self.subTest(name=name):
6812 self.assertEqual(tz_act, tz_exp)
6813
6814 dt1 = datetime(2000, 2, 4, tzinfo=tz_act)
6815 dt2 = datetime(2000, 2, 4, tzinfo=tz_exp)
6816
6817 self.assertEqual(dt1, dt2)
6818 self.assertEqual(dt1.tzname(), dt2.tzname())
6819
6820 dt_utc = datetime(2000, 2, 4, 5, tzinfo=timezone.utc)
6821
6822 self.assertEqual(dt1.astimezone(timezone.utc), dt_utc)
6823
6824 def test_PyDateTime_DELTA_GET(self):
6825 class TimeDeltaSubclass(timedelta):
6826 pass
6827
6828 for klass in [timedelta, TimeDeltaSubclass]:
6829 for args in [(26, 55, 99999), (26, 55, 99999)]:
6830 d = klass(*args)
6831 with self.subTest(cls=klass, date=args):
6832 days, seconds, microseconds = _testcapi.PyDateTime_DELTA_GET(d)
6833
6834 self.assertEqual(days, d.days)
6835 self.assertEqual(seconds, d.seconds)
6836 self.assertEqual(microseconds, d.microseconds)
6837
6838 def test_PyDateTime_GET(self):
6839 class DateSubclass(date):
6840 pass
6841
6842 for klass in [date, DateSubclass]:
6843 for args in [(2000, 1, 2), (2012, 2, 29)]:
6844 d = klass(*args)
6845 with self.subTest(cls=klass, date=args):
6846 year, month, day = _testcapi.PyDateTime_GET(d)
6847
6848 self.assertEqual(year, d.year)
6849 self.assertEqual(month, d.month)
6850 self.assertEqual(day, d.day)
6851
6852 def test_PyDateTime_DATE_GET(self):
6853 class DateTimeSubclass(datetime):
6854 pass
6855
6856 for klass in [datetime, DateTimeSubclass]:
6857 for args in [(1993, 8, 26, 22, 12, 55, 99999),
6858 (1993, 8, 26, 22, 12, 55, 99999,
6859 timezone.utc)]:
6860 d = klass(*args)
6861 with self.subTest(cls=klass, date=args):
6862 hour, minute, second, microsecond, tzinfo = \
6863 _testcapi.PyDateTime_DATE_GET(d)
6864
6865 self.assertEqual(hour, d.hour)
6866 self.assertEqual(minute, d.minute)
6867 self.assertEqual(second, d.second)
6868 self.assertEqual(microsecond, d.microsecond)
6869 self.assertIs(tzinfo, d.tzinfo)
6870
6871 def test_PyDateTime_TIME_GET(self):
6872 class TimeSubclass(time):
6873 pass
6874
6875 for klass in [time, TimeSubclass]:
6876 for args in [(12, 30, 20, 10),
6877 (12, 30, 20, 10, timezone.utc)]:
6878 d = klass(*args)
6879 with self.subTest(cls=klass, date=args):
6880 hour, minute, second, microsecond, tzinfo = \
6881 _testcapi.PyDateTime_TIME_GET(d)
6882
6883 self.assertEqual(hour, d.hour)
6884 self.assertEqual(minute, d.minute)
6885 self.assertEqual(second, d.second)
6886 self.assertEqual(microsecond, d.microsecond)
6887 self.assertIs(tzinfo, d.tzinfo)
6888
6889 def test_timezones_offset_zero(self):
6890 utc0, utc1, non_utc = _testcapi.get_timezones_offset_zero()
6891
6892 with self.subTest(testname="utc0"):
6893 self.assertIs(utc0, timezone.utc)
6894
6895 with self.subTest(testname="utc1"):
6896 self.assertIs(utc1, timezone.utc)
6897
6898 with self.subTest(testname="non_utc"):
6899 self.assertIsNot(non_utc, timezone.utc)
6900
6901 non_utc_exp = timezone(timedelta(hours=0), "")
6902
6903 self.assertEqual(non_utc, non_utc_exp)
6904
6905 dt1 = datetime(2000, 2, 4, tzinfo=non_utc)
6906 dt2 = datetime(2000, 2, 4, tzinfo=non_utc_exp)
6907
6908 self.assertEqual(dt1, dt2)
6909 self.assertEqual(dt1.tzname(), dt2.tzname())
6910
6911 def test_check_date(self):
6912 class DateSubclass(date):
6913 pass
6914
6915 d = date(2011, 1, 1)
6916 ds = DateSubclass(2011, 1, 1)
6917 dt = datetime(2011, 1, 1)
6918
6919 is_date = _testcapi.datetime_check_date
6920
6921 # Check the ones that should be valid
6922 self.assertTrue(is_date(d))
6923 self.assertTrue(is_date(dt))
6924 self.assertTrue(is_date(ds))
6925 self.assertTrue(is_date(d, True))
6926
6927 # Check that the subclasses do not match exactly
6928 self.assertFalse(is_date(dt, True))
6929 self.assertFalse(is_date(ds, True))
6930
6931 # Check that various other things are not dates at all
6932 args = [tuple(), list(), 1, '2011-01-01',
6933 timedelta(1), timezone.utc, time(12, 00)]
6934 for arg in args:
6935 for exact in (True, False):
6936 with self.subTest(arg=arg, exact=exact):
6937 self.assertFalse(is_date(arg, exact))
6938
6939 def test_check_time(self):
6940 class TimeSubclass(time):
6941 pass
6942
6943 t = time(12, 30)
6944 ts = TimeSubclass(12, 30)
6945
6946 is_time = _testcapi.datetime_check_time
6947
6948 # Check the ones that should be valid
6949 self.assertTrue(is_time(t))
6950 self.assertTrue(is_time(ts))
6951 self.assertTrue(is_time(t, True))
6952
6953 # Check that the subclass does not match exactly
6954 self.assertFalse(is_time(ts, True))
6955
6956 # Check that various other things are not times
6957 args = [tuple(), list(), 1, '2011-01-01',
6958 timedelta(1), timezone.utc, date(2011, 1, 1)]
6959
6960 for arg in args:
6961 for exact in (True, False):
6962 with self.subTest(arg=arg, exact=exact):
6963 self.assertFalse(is_time(arg, exact))
6964
6965 def test_check_datetime(self):
6966 class DateTimeSubclass(datetime):
6967 pass
6968
6969 dt = datetime(2011, 1, 1, 12, 30)
6970 dts = DateTimeSubclass(2011, 1, 1, 12, 30)
6971
6972 is_datetime = _testcapi.datetime_check_datetime
6973
6974 # Check the ones that should be valid
6975 self.assertTrue(is_datetime(dt))
6976 self.assertTrue(is_datetime(dts))
6977 self.assertTrue(is_datetime(dt, True))
6978
6979 # Check that the subclass does not match exactly
6980 self.assertFalse(is_datetime(dts, True))
6981
6982 # Check that various other things are not datetimes
6983 args = [tuple(), list(), 1, '2011-01-01',
6984 timedelta(1), timezone.utc, date(2011, 1, 1)]
6985
6986 for arg in args:
6987 for exact in (True, False):
6988 with self.subTest(arg=arg, exact=exact):
6989 self.assertFalse(is_datetime(arg, exact))
6990
6991 def test_check_delta(self):
6992 class TimeDeltaSubclass(timedelta):
6993 pass
6994
6995 td = timedelta(1)
6996 tds = TimeDeltaSubclass(1)
6997
6998 is_timedelta = _testcapi.datetime_check_delta
6999
7000 # Check the ones that should be valid
7001 self.assertTrue(is_timedelta(td))
7002 self.assertTrue(is_timedelta(tds))
7003 self.assertTrue(is_timedelta(td, True))
7004
7005 # Check that the subclass does not match exactly
7006 self.assertFalse(is_timedelta(tds, True))
7007
7008 # Check that various other things are not timedeltas
7009 args = [tuple(), list(), 1, '2011-01-01',
7010 timezone.utc, date(2011, 1, 1), datetime(2011, 1, 1)]
7011
7012 for arg in args:
7013 for exact in (True, False):
7014 with self.subTest(arg=arg, exact=exact):
7015 self.assertFalse(is_timedelta(arg, exact))
7016
7017 def test_check_tzinfo(self):
7018 class TZInfoSubclass(tzinfo):
7019 pass
7020
7021 tzi = tzinfo()
7022 tzis = TZInfoSubclass()
7023 tz = timezone(timedelta(hours=-5))
7024
7025 is_tzinfo = _testcapi.datetime_check_tzinfo
7026
7027 # Check the ones that should be valid
7028 self.assertTrue(is_tzinfo(tzi))
7029 self.assertTrue(is_tzinfo(tz))
7030 self.assertTrue(is_tzinfo(tzis))
7031 self.assertTrue(is_tzinfo(tzi, True))
7032
7033 # Check that the subclasses do not match exactly
7034 self.assertFalse(is_tzinfo(tz, True))
7035 self.assertFalse(is_tzinfo(tzis, True))
7036
7037 # Check that various other things are not tzinfos
7038 args = [tuple(), list(), 1, '2011-01-01',
7039 date(2011, 1, 1), datetime(2011, 1, 1)]
7040
7041 for arg in args:
7042 for exact in (True, False):
7043 with self.subTest(arg=arg, exact=exact):
7044 self.assertFalse(is_tzinfo(arg, exact))
7045
7046 def test_date_from_date(self):
7047 exp_date = date(1993, 8, 26)
7048
7049 for macro in False, True:
7050 with self.subTest(macro=macro):
7051 c_api_date = _testcapi.get_date_fromdate(
7052 macro,
7053 exp_date.year,
7054 exp_date.month,
7055 exp_date.day)
7056
7057 self.assertEqual(c_api_date, exp_date)
7058
7059 def test_datetime_from_dateandtime(self):
7060 exp_date = datetime(1993, 8, 26, 22, 12, 55, 99999)
7061
7062 for macro in False, True:
7063 with self.subTest(macro=macro):
7064 c_api_date = _testcapi.get_datetime_fromdateandtime(
7065 macro,
7066 exp_date.year,
7067 exp_date.month,
7068 exp_date.day,
7069 exp_date.hour,
7070 exp_date.minute,
7071 exp_date.second,
7072 exp_date.microsecond)
7073
7074 self.assertEqual(c_api_date, exp_date)
7075
7076 def test_datetime_from_dateandtimeandfold(self):
7077 exp_date = datetime(1993, 8, 26, 22, 12, 55, 99999)
7078
7079 for fold in [0, 1]:
7080 for macro in False, True:
7081 with self.subTest(macro=macro, fold=fold):
7082 c_api_date = _testcapi.get_datetime_fromdateandtimeandfold(
7083 macro,
7084 exp_date.year,
7085 exp_date.month,
7086 exp_date.day,
7087 exp_date.hour,
7088 exp_date.minute,
7089 exp_date.second,
7090 exp_date.microsecond,
7091 exp_date.fold)
7092
7093 self.assertEqual(c_api_date, exp_date)
7094 self.assertEqual(c_api_date.fold, exp_date.fold)
7095
7096 def test_time_from_time(self):
7097 exp_time = time(22, 12, 55, 99999)
7098
7099 for macro in False, True:
7100 with self.subTest(macro=macro):
7101 c_api_time = _testcapi.get_time_fromtime(
7102 macro,
7103 exp_time.hour,
7104 exp_time.minute,
7105 exp_time.second,
7106 exp_time.microsecond)
7107
7108 self.assertEqual(c_api_time, exp_time)
7109
7110 def test_time_from_timeandfold(self):
7111 exp_time = time(22, 12, 55, 99999)
7112
7113 for fold in [0, 1]:
7114 for macro in False, True:
7115 with self.subTest(macro=macro, fold=fold):
7116 c_api_time = _testcapi.get_time_fromtimeandfold(
7117 macro,
7118 exp_time.hour,
7119 exp_time.minute,
7120 exp_time.second,
7121 exp_time.microsecond,
7122 exp_time.fold)
7123
7124 self.assertEqual(c_api_time, exp_time)
7125 self.assertEqual(c_api_time.fold, exp_time.fold)
7126
7127 def test_delta_from_dsu(self):
7128 exp_delta = timedelta(26, 55, 99999)
7129
7130 for macro in False, True:
7131 with self.subTest(macro=macro):
7132 c_api_delta = _testcapi.get_delta_fromdsu(
7133 macro,
7134 exp_delta.days,
7135 exp_delta.seconds,
7136 exp_delta.microseconds)
7137
7138 self.assertEqual(c_api_delta, exp_delta)
7139
7140 def test_date_from_timestamp(self):
7141 ts = datetime(1995, 4, 12).timestamp()
7142
7143 for macro in False, True:
7144 with self.subTest(macro=macro):
7145 d = _testcapi.get_date_fromtimestamp(int(ts), macro)
7146
7147 self.assertEqual(d, date(1995, 4, 12))
7148
7149 def test_datetime_from_timestamp(self):
7150 cases = [
7151 ((1995, 4, 12), None, False),
7152 ((1995, 4, 12), None, True),
7153 ((1995, 4, 12), timezone(timedelta(hours=1)), True),
7154 ((1995, 4, 12, 14, 30), None, False),
7155 ((1995, 4, 12, 14, 30), None, True),
7156 ((1995, 4, 12, 14, 30), timezone(timedelta(hours=1)), True),
7157 ]
7158
7159 from_timestamp = _testcapi.get_datetime_fromtimestamp
7160 for case in cases:
7161 for macro in False, True:
7162 with self.subTest(case=case, macro=macro):
7163 dtup, tzinfo, usetz = case
7164 dt_orig = datetime(*dtup, tzinfo=tzinfo)
7165 ts = int(dt_orig.timestamp())
7166
7167 dt_rt = from_timestamp(ts, tzinfo, usetz, macro)
7168
7169 self.assertEqual(dt_orig, dt_rt)
7170
7171 def test_type_check_in_subinterp(self):
7172 # iOS requires the use of the custom framework loader,
7173 # not the ExtensionFileLoader.
7174 if sys.platform == "ios":
7175 extension_loader = "AppleFrameworkLoader"
7176 else:
7177 extension_loader = "ExtensionFileLoader"
7178
7179 script = textwrap.dedent(f"""
7180 if {_interpreters is None}:
7181 import _testcapi as module
7182 module.test_datetime_capi()
7183 else:
7184 import importlib.machinery
7185 import importlib.util
7186 fullname = '_testcapi_datetime'
7187 origin = importlib.util.find_spec('_testcapi').origin
7188 loader = importlib.machinery.{extension_loader}(fullname, origin)
7189 spec = importlib.util.spec_from_loader(fullname, loader)
7190 module = importlib.util.module_from_spec(spec)
7191 spec.loader.exec_module(module)
7192
7193 def run(type_checker, obj):
7194 if not type_checker(obj, True):
7195 raise TypeError(f'{{type(obj)}} is not C API type')
7196
7197 import _datetime
7198 run(module.datetime_check_date, _datetime.date.today())
7199 run(module.datetime_check_datetime, _datetime.datetime.now())
7200 run(module.datetime_check_time, _datetime.time(12, 30))
7201 run(module.datetime_check_delta, _datetime.timedelta(1))
7202 run(module.datetime_check_tzinfo, _datetime.tzinfo())
7203 """)
7204 if _interpreters is None:
7205 ret = support.run_in_subinterp(script)
7206 self.assertEqual(ret, 0)
7207 else:
7208 for name in ('isolated', 'legacy'):
7209 with self.subTest(name):
7210 config = _interpreters.new_config(name).__dict__
7211 ret = support.run_in_subinterp_with_config(script, **config)
7212 self.assertEqual(ret, 0)
7213
7214
7215 class ExtensionModuleTests(unittest.TestCase):
7216
7217 def setUp(self):
7218 if self.__class__.__name__.endswith('Pure'):
7219 self.skipTest('Not relevant in pure Python')
7220
7221 @support.cpython_only
7222 def test_gh_120161(self):
7223 with self.subTest('simple'):
7224 script = textwrap.dedent("""
7225 import datetime
7226 from _ast import Tuple
7227 f = lambda: None
7228 Tuple.dims = property(f, f)
7229
7230 class tzutc(datetime.tzinfo):
7231 pass
7232 """)
7233 script_helper.assert_python_ok('-c', script)
7234
7235 with self.subTest('complex'):
7236 script = textwrap.dedent("""
7237 import asyncio
7238 import datetime
7239 from typing import Type
7240
7241 class tzutc(datetime.tzinfo):
7242 pass
7243 _EPOCHTZ = datetime.datetime(1970, 1, 1, tzinfo=tzutc())
7244
7245 class FakeDateMeta(type):
7246 def __instancecheck__(self, obj):
7247 return True
7248 class FakeDate(datetime.date, metaclass=FakeDateMeta):
7249 pass
7250 def pickle_fake_date(datetime_) -> Type[FakeDate]:
7251 # A pickle function for FakeDate
7252 return FakeDate
7253 """)
7254 script_helper.assert_python_ok('-c', script)
7255
7256 def test_update_type_cache(self):
7257 # gh-120782
7258 script = textwrap.dedent("""
7259 import sys
7260 for i in range(5):
7261 import _datetime
7262 assert _datetime.date.max > _datetime.date.min
7263 assert _datetime.time.max > _datetime.time.min
7264 assert _datetime.datetime.max > _datetime.datetime.min
7265 assert _datetime.timedelta.max > _datetime.timedelta.min
7266 assert _datetime.date.__dict__["min"] is _datetime.date.min
7267 assert _datetime.date.__dict__["max"] is _datetime.date.max
7268 assert _datetime.date.__dict__["resolution"] is _datetime.date.resolution
7269 assert _datetime.time.__dict__["min"] is _datetime.time.min
7270 assert _datetime.time.__dict__["max"] is _datetime.time.max
7271 assert _datetime.time.__dict__["resolution"] is _datetime.time.resolution
7272 assert _datetime.datetime.__dict__["min"] is _datetime.datetime.min
7273 assert _datetime.datetime.__dict__["max"] is _datetime.datetime.max
7274 assert _datetime.datetime.__dict__["resolution"] is _datetime.datetime.resolution
7275 assert _datetime.timedelta.__dict__["min"] is _datetime.timedelta.min
7276 assert _datetime.timedelta.__dict__["max"] is _datetime.timedelta.max
7277 assert _datetime.timedelta.__dict__["resolution"] is _datetime.timedelta.resolution
7278 assert _datetime.timezone.__dict__["min"] is _datetime.timezone.min
7279 assert _datetime.timezone.__dict__["max"] is _datetime.timezone.max
7280 assert _datetime.timezone.__dict__["utc"] is _datetime.timezone.utc
7281 assert isinstance(_datetime.timezone.min, _datetime.tzinfo)
7282 assert isinstance(_datetime.timezone.max, _datetime.tzinfo)
7283 assert isinstance(_datetime.timezone.utc, _datetime.tzinfo)
7284 del sys.modules['_datetime']
7285 """)
7286 script_helper.assert_python_ok('-c', script)
7287
7288 def test_concurrent_initialization_subinterpreter(self):
7289 # gh-136421: Concurrent initialization of _datetime across multiple
7290 # interpreters wasn't thread-safe due to its static types.
7291
7292 # Run in a subprocess to ensure we get a clean version of _datetime
7293 script = """if True:
7294 from concurrent.futures import InterpreterPoolExecutor
7295
7296 def func():
7297 import _datetime
7298 print('a', end='')
7299
7300 with InterpreterPoolExecutor() as executor:
7301 for _ in range(8):
7302 executor.submit(func)
7303 """
7304 rc, out, err = script_helper.assert_python_ok("-c", script)
7305 self.assertEqual(rc, 0)
7306 self.assertEqual(out, b"a" * 8)
7307 self.assertEqual(err, b"")
7308
7309 # Now test against concurrent reinitialization
7310 script = "import _datetime\n" + script
7311 rc, out, err = script_helper.assert_python_ok("-c", script)
7312 self.assertEqual(rc, 0)
7313 self.assertEqual(out, b"a" * 8)
7314 self.assertEqual(err, b"")
7315
7316
7317 def load_tests(loader, standard_tests, pattern):
7318 standard_tests.addTest(ZoneInfoCompleteTest())
7319 return standard_tests
7320
7321
7322 if __name__ == "__main__":
7323 unittest.main()