Debian Codegraph @

Lib/test/datetimetester.py

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