-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathadafruit_datetime.py
executable file
·1803 lines (1543 loc) · 59 KB
/
adafruit_datetime.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-FileCopyrightText: 2001-2021 Python Software Foundation.All rights reserved.
# SPDX-FileCopyrightText: 2000 BeOpen.com. All rights reserved.
# SPDX-FileCopyrightText: 1995-2001 Corporation for National Research Initiatives.
# All rights reserved.
# SPDX-FileCopyrightText: 1995-2001 Corporation for National Research Initiatives.
# All rights reserved.
# SPDX-FileCopyrightText: 1991-1995 Stichting Mathematisch Centrum. All rights reserved.
# SPDX-FileCopyrightText: 2017 Paul Sokolovsky
# SPDX-License-Identifier: Python-2.0
"""
`adafruit_datetime`
================================================================================
Concrete date/time and related types.
See http://www.iana.org/time-zones/repository/tz-link.html for
time zone and DST data sources.
Implementation Notes
--------------------
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://github.com/adafruit/circuitpython/releases
"""
# pylint: disable=too-many-lines
import time as _time
import math as _math
import re as _re
from micropython import const
try:
from typing import Any, Union, Optional, Tuple, Sequence, List
except ImportError:
pass
__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_DateTime.git"
# Constants
MINYEAR = const(1)
MAXYEAR = const(9999)
_MAXORDINAL = const(3652059)
_DI400Y = const(146097)
_DI100Y = const(36524)
_DI4Y = const(1461)
# https://svn.python.org/projects/sandbox/trunk/datetime/datetime.py
_DAYS_IN_MONTH = (None, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
_DAYS_BEFORE_MONTH = (None, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334)
# Month and day names. For localized versions, see the calendar module.
_MONTHNAMES = (
None,
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
)
_DAYNAMES = (None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
_INVALID_ISO_ERROR = "Invalid isoformat string: '{}'"
# Utility functions - universal
def _cmp(obj_x: Any, obj_y: Any) -> int:
return 0 if obj_x == obj_y else 1 if obj_x > obj_y else -1
def _cmperror(
obj_x: Union["datetime", "timedelta"], obj_y: Union["datetime", "timedelta"]
) -> None:
raise TypeError(
"can't compare '%s' to '%s'" % (type(obj_x).__name__, type(obj_y).__name__)
)
# Utility functions - time
def _check_time_fields(
hour: int, minute: int, second: int, microsecond: int, fold: int
) -> None:
if not isinstance(hour, int):
raise TypeError("Hour expected as int")
if not 0 <= hour <= 23:
raise ValueError("hour must be in 0..23", hour)
if not 0 <= minute <= 59:
raise ValueError("minute must be in 0..59", minute)
if not 0 <= second <= 59:
raise ValueError("second must be in 0..59", second)
if not 0 <= microsecond <= 999999:
raise ValueError("microsecond must be in 0..999999", microsecond)
if fold not in (0, 1): # from CPython API
raise ValueError("fold must be either 0 or 1", fold)
def _check_utc_offset(name: str, offset: "timedelta") -> None:
assert name in ("utcoffset", "dst")
if offset is None:
return
if not isinstance(offset, timedelta):
raise TypeError(
"tzinfo.%s() must return None "
"or timedelta, not '%s'" % (name, type(offset))
)
if offset % timedelta(minutes=1) or offset.microseconds:
raise ValueError(
"tzinfo.%s() must return a whole number "
"of minutes, got %s" % (name, offset)
)
if not -timedelta(1) < offset < timedelta(1):
raise ValueError(
"%s()=%s, must be must be strictly between"
" -timedelta(hours=24) and timedelta(hours=24)" % (name, offset)
)
# pylint: disable=invalid-name
def _format_offset(off: "timedelta") -> str:
s = ""
if off is not None:
if off.days < 0:
sign = "-"
off = -off
else:
sign = "+"
hh, mm = divmod(off, timedelta(hours=1))
mm, ss = divmod(mm, timedelta(minutes=1))
s += "%s%02d:%02d" % (sign, hh, mm)
if ss or ss.microseconds:
s += ":%02d" % ss.seconds
if ss.microseconds:
s += ".%06d" % ss.microseconds
return s
# Utility functions - timezone
def _check_tzname(name: Optional[str]) -> None:
""" "Just raise TypeError if the arg isn't None or a string."""
if name is not None and not isinstance(name, str):
raise TypeError(
"tzinfo.tzname() must return None or string, " "not '%s'" % type(name)
)
def _check_tzinfo_arg(time_zone: Optional["tzinfo"]):
if time_zone is not None and not isinstance(time_zone, tzinfo):
raise TypeError("tzinfo argument must be None or of a tzinfo subclass")
# Utility functions - date
def _is_leap(year: int) -> bool:
"year -> True if leap year, else False."
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def _days_in_month(year: int, month: int) -> int:
"year, month -> number of days in that month in that year."
assert 1 <= month <= 12, month
if month == 2 and _is_leap(year):
return 29
return _DAYS_IN_MONTH[month]
def _check_date_fields(year: int, month: int, day: int) -> None:
if not isinstance(year, int):
raise TypeError("int expected")
if not MINYEAR <= year <= MAXYEAR:
raise ValueError("year must be in %d..%d" % (MINYEAR, MAXYEAR), year)
if not 1 <= month <= 12:
raise ValueError("month must be in 1..12", month)
dim = _days_in_month(year, month)
if not 1 <= day <= dim:
raise ValueError("day must be in 1..%d" % dim, day)
def _days_before_month(year: int, month: int) -> int:
"year, month -> number of days in year preceding first day of month."
assert 1 <= month <= 12, "month must be in 1..12"
return _DAYS_BEFORE_MONTH[month] + (month > 2 and _is_leap(year))
def _days_before_year(year: int) -> int:
"year -> number of days before January 1st of year."
year = year - 1
return year * 365 + year // 4 - year // 100 + year // 400
def _ymd2ord(year: int, month: int, day: int) -> int:
"year, month, day -> ordinal, considering 01-Jan-0001 as day 1."
assert 1 <= month <= 12, "month must be in 1..12"
dim = _days_in_month(year, month)
assert 1 <= day <= dim, "day must be in 1..%d" % dim
return _days_before_year(year) + _days_before_month(year, month) + day
# pylint: disable=too-many-arguments
def _build_struct_time(
tm_year: int,
tm_month: int,
tm_mday: int,
tm_hour: int,
tm_min: int,
tm_sec: int,
tm_isdst: int,
) -> _time.struct_time:
tm_wday = (_ymd2ord(tm_year, tm_month, tm_mday) + 6) % 7
tm_yday = _days_before_month(tm_year, tm_month) + tm_mday
return _time.struct_time(
(
tm_year,
tm_month,
tm_mday,
tm_hour,
tm_min,
tm_sec,
tm_wday,
tm_yday,
tm_isdst,
)
)
# pylint: disable=invalid-name
def _format_time(hh: int, mm: int, ss: int, us: int, timespec: str = "auto") -> str:
if timespec != "auto":
raise NotImplementedError("Only default timespec supported")
if us:
spec = "{:02d}:{:02d}:{:02d}.{:06d}"
else:
spec = "{:02d}:{:02d}:{:02d}"
fmt = spec
return fmt.format(hh, mm, ss, us)
# A 4-year cycle has an extra leap day over what we'd get from pasting
# together 4 single years.
assert _DI4Y == 4 * 365 + 1
# Similarly, a 400-year cycle has an extra leap day over what we'd get from
# pasting together 4 100-year cycles.
assert _DI400Y == 4 * _DI100Y + 1
# OTOH, a 100-year cycle has one fewer leap day than we'd get from
# pasting together 25 4-year cycles.
assert _DI100Y == 25 * _DI4Y - 1
def _ord2ymd(n: int) -> Tuple[int, int, int]:
"ordinal -> (year, month, day), considering 01-Jan-0001 as day 1."
# n is a 1-based index, starting at 1-Jan-1. The pattern of leap years
# repeats exactly every 400 years. The basic strategy is to find the
# closest 400-year boundary at or before n, then work with the offset
# from that boundary to n. Life is much clearer if we subtract 1 from
# n first -- then the values of n at 400-year boundaries are exactly
# those divisible by _DI400Y:
#
# D M Y n n-1
# -- --- ---- ---------- ----------------
# 31 Dec -400 -_DI400Y -_DI400Y -1
# 1 Jan -399 -_DI400Y +1 -_DI400Y 400-year boundary
# ...
# 30 Dec 000 -1 -2
# 31 Dec 000 0 -1
# 1 Jan 001 1 0 400-year boundary
# 2 Jan 001 2 1
# 3 Jan 001 3 2
# ...
# 31 Dec 400 _DI400Y _DI400Y -1
# 1 Jan 401 _DI400Y +1 _DI400Y 400-year boundary
n -= 1
n400, n = divmod(n, _DI400Y)
year = n400 * 400 + 1 # ..., -399, 1, 401, ...
# Now n is the (non-negative) offset, in days, from January 1 of year, to
# the desired date. Now compute how many 100-year cycles precede n.
# Note that it's possible for n100 to equal 4! In that case 4 full
# 100-year cycles precede the desired day, which implies the desired
# day is December 31 at the end of a 400-year cycle.
n100, n = divmod(n, _DI100Y)
# Now compute how many 4-year cycles precede it.
n4, n = divmod(n, _DI4Y)
# And now how many single years. Again n1 can be 4, and again meaning
# that the desired day is December 31 at the end of the 4-year cycle.
n1, n = divmod(n, 365)
year += n100 * 100 + n4 * 4 + n1
if n1 == 4 or n100 == 4:
assert n == 0
return year - 1, 12, 31
# Now the year is correct, and n is the offset from January 1. We find
# the month via an estimate that's either exact or one too large.
leapyear = n1 == 3 and (n4 != 24 or n100 == 3)
assert leapyear == _is_leap(year)
month = (n + 50) >> 5
preceding = _DAYS_BEFORE_MONTH[month] + (month > 2 and leapyear)
if preceding > n: # estimate is too large
month -= 1
preceding -= _DAYS_IN_MONTH[month] + (month == 2 and leapyear)
n -= preceding
assert 0 <= n < _days_in_month(year, month)
# Now the year and month are correct, and n is the offset from the
# start of that month: we're done!
return year, month, n + 1
class timedelta:
"""A timedelta object represents a duration, the difference between two dates or times."""
# pylint: disable=too-many-arguments, too-many-locals, too-many-statements
def __new__(
cls,
days: int = 0,
seconds: int = 0,
microseconds: int = 0,
milliseconds: int = 0,
minutes: int = 0,
hours: int = 0,
weeks: int = 0,
) -> "timedelta":
# Check that all inputs are ints or floats.
if not all(
isinstance(i, (int, float))
for i in [days, seconds, microseconds, milliseconds, minutes, hours, weeks]
):
raise TypeError("Kwargs to this function must be int or float.")
# Final values, all integer.
# s and us fit in 32-bit signed ints; d isn't bounded.
d = s = us = 0
# Normalize everything to days, seconds, microseconds.
days += weeks * 7
seconds += minutes * 60 + hours * 3600
microseconds += milliseconds * 1000
# Get rid of all fractions, and normalize s and us.
if isinstance(days, float):
dayfrac, days = _math.modf(days)
daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.0 * 3600.0))
assert daysecondswhole == int(daysecondswhole) # can't overflow
s = int(daysecondswhole)
assert days == int(days)
d = int(days)
else:
daysecondsfrac = 0.0
d = days
assert isinstance(daysecondsfrac, float)
assert abs(daysecondsfrac) <= 1.0
assert isinstance(d, int)
assert abs(s) <= 24 * 3600
# days isn't referenced again before redefinition
if isinstance(seconds, float):
secondsfrac, seconds = _math.modf(seconds)
assert seconds == int(seconds)
seconds = int(seconds)
secondsfrac += daysecondsfrac
assert abs(secondsfrac) <= 2.0
else:
secondsfrac = daysecondsfrac
# daysecondsfrac isn't referenced again
assert isinstance(secondsfrac, float)
assert abs(secondsfrac) <= 2.0
assert isinstance(seconds, int)
days, seconds = divmod(seconds, 24 * 3600)
d += days
s += int(seconds) # can't overflow
assert isinstance(s, int)
assert abs(s) <= 2 * 24 * 3600
# seconds isn't referenced again before redefinition
usdouble = secondsfrac * 1e6
assert abs(usdouble) < 2.1e6 # exact value not critical
# secondsfrac isn't referenced again
if isinstance(microseconds, float):
microseconds = round(microseconds + usdouble)
seconds, microseconds = divmod(microseconds, 1000000)
days, seconds = divmod(seconds, 24 * 3600)
d += days
s += seconds
else:
microseconds = int(microseconds)
seconds, microseconds = divmod(microseconds, 1000000)
days, seconds = divmod(seconds, 24 * 3600)
d += days
s += seconds
microseconds = round(microseconds + usdouble)
assert isinstance(s, int)
assert isinstance(microseconds, int)
assert abs(s) <= 3 * 24 * 3600
assert abs(microseconds) < 3.1e6
# Just a little bit of carrying possible for microseconds and seconds.
seconds, us = divmod(microseconds, 1000000)
s += seconds
days, s = divmod(s, 24 * 3600)
d += days
assert isinstance(d, int)
assert isinstance(s, int) and 0 <= s < 24 * 3600
assert isinstance(us, int) and 0 <= us < 1000000
if abs(d) > 999999999:
raise OverflowError("timedelta # of days is too large: %d" % d)
self = object.__new__(cls)
self._days = d
self._seconds = s
self._microseconds = us
self._hashcode = -1
return self
# Instance attributes (read-only)
@property
def days(self) -> int:
"""Days, Between -999999999 and 999999999 inclusive"""
return self._days
@property
def seconds(self) -> int:
"""Seconds, Between 0 and 86399 inclusive"""
return self._seconds
@property
def microseconds(self) -> int:
"""Microseconds, Between 0 and 999999 inclusive"""
return self._microseconds
# Instance methods
def total_seconds(self) -> float:
"""Return the total number of seconds contained in the duration."""
# If the duration is less than a threshold duration, and microseconds
# is nonzero, then the result is a float. Otherwise, the result is a
# (possibly long) integer. This differs from standard Python where the
# result is always a float, because the precision of CircuitPython
# floats is considerably smaller than on standard Python.
seconds = self._days * 86400 + self._seconds
if self._microseconds != 0 and abs(seconds) < (1 << 21):
seconds += self._microseconds / 10**6
return seconds
def __repr__(self) -> str:
args = []
if self._days:
args.append("days=%d" % self._days)
if self._seconds:
args.append("seconds=%d" % self._seconds)
if self._microseconds:
args.append("microseconds=%d" % self._microseconds)
if not args:
args.append("0")
return "%s.%s(%s)" % (
self.__class__.__module__,
self.__class__.__qualname__,
", ".join(args),
)
def __str__(self) -> str:
mm, ss = divmod(self._seconds, 60)
hh, mm = divmod(mm, 60)
s = "%d:%02d:%02d" % (hh, mm, ss)
if self._days:
def plural(n):
return n, abs(n) != 1 and "s" or ""
s = ("%d day%s, " % plural(self._days)) + s
if self._microseconds:
s = s + ".%06d" % self._microseconds
return s
# Supported operations
def __neg__(self) -> "timedelta":
return timedelta(-self._days, -self._seconds, -self._microseconds)
def __add__(self, other: "timedelta") -> "timedelta":
if isinstance(other, timedelta):
return timedelta(
self._days + other._days,
self._seconds + other._seconds,
self._microseconds + other._microseconds,
)
return NotImplemented
def __sub__(self, other: "timedelta") -> "timedelta":
if isinstance(other, timedelta):
return timedelta(
self._days - other._days,
self._seconds - other._seconds,
self._microseconds - other._microseconds,
)
return NotImplemented
def _to_microseconds(self) -> int:
return (self._days * (24 * 3600) + self._seconds) * 1000000 + self._microseconds
def __floordiv__(self, other: Union[int, "timedelta"]) -> Union[int, "timedelta"]:
if not isinstance(other, (int, timedelta)):
return NotImplemented
usec = self._to_microseconds()
if isinstance(other, timedelta):
return usec // other._to_microseconds()
return timedelta(0, 0, usec // other)
def __mod__(self, other: "timedelta") -> "timedelta":
if isinstance(other, timedelta):
r = self._to_microseconds() % other._to_microseconds()
return timedelta(0, 0, r)
return NotImplemented
def __divmod__(self, other: "timedelta") -> "timedelta":
if isinstance(other, timedelta):
q, r = divmod(self._to_microseconds(), other._to_microseconds())
return q, timedelta(0, 0, r)
return NotImplemented
def __mul__(self, other: float) -> "timedelta":
if isinstance(other, int):
# for CPython compatibility, we cannot use
# our __class__ here, but need a real timedelta
return timedelta(
self._days * other, self._seconds * other, self._microseconds * other
)
if isinstance(other, float):
# a, b = other.as_integer_ratio()
# return self * a / b
usec = self._to_microseconds()
return timedelta(0, 0, round(usec * other))
return NotImplemented
__rmul__ = __mul__
# Supported comparisons
def __eq__(self, other: Any) -> bool:
if not isinstance(other, timedelta):
return False
return self._cmp(other) == 0
def __ne__(self, other: "timedelta") -> bool:
if not isinstance(other, timedelta):
return True
return self._cmp(other) != 0
def __le__(self, other: "timedelta") -> bool:
if not isinstance(other, timedelta):
_cmperror(self, other)
return self._cmp(other) <= 0
def __lt__(self, other: "timedelta") -> bool:
if not isinstance(other, timedelta):
_cmperror(self, other)
return self._cmp(other) < 0
def __ge__(self, other: "timedelta") -> bool:
if not isinstance(other, timedelta):
_cmperror(self, other)
return self._cmp(other) >= 0
def __gt__(self, other: "timedelta") -> bool:
if not isinstance(other, timedelta):
_cmperror(self, other)
return self._cmp(other) > 0
# pylint: disable=no-self-use, protected-access
def _cmp(self, other: "timedelta") -> int:
assert isinstance(other, timedelta)
return _cmp(self._getstate(), other._getstate())
def __bool__(self) -> bool:
return self._days != 0 or self._seconds != 0 or self._microseconds != 0
def _getstate(self) -> Tuple[int, int, int]:
return (self._days, self._seconds, self._microseconds)
# pylint: disable=no-self-use
class tzinfo:
"""This is an abstract base class, meaning that this class should not
be instantiated directly. Define a subclass of tzinfo to capture information
about a particular time zone.
"""
def utcoffset(self, dt: "datetime") -> timedelta:
"""Return offset of local time from UTC, as a timedelta
object that is positive east of UTC.
"""
raise NotImplementedError("tzinfo subclass must override utcoffset()")
def tzname(self, dt: "datetime") -> str:
"""Return the time zone name corresponding to the datetime object dt, as a string."""
raise NotImplementedError("tzinfo subclass must override tzname()")
def dst(self, dt: "datetime") -> None: # pylint: disable=unused-argument
"""Return the DST setting correspinding to the datetime object dt, as a number.
DST usage is currently not implemented for this library.
"""
return None
# tzinfo is an abstract base class, disabling for self._offset
# pylint: disable=no-member
def fromutc(self, dt: "datetime") -> "datetime":
"datetime in UTC -> datetime in local time."
if not isinstance(dt, datetime):
raise TypeError("fromutc() requires a datetime argument")
if dt.tzinfo is not self:
raise ValueError("dt.tzinfo is not self")
dtoff = dt.utcoffset()
if dtoff is None:
raise ValueError("fromutc() requires a non-None utcoffset() result")
return dt + self._offset
class date:
"""A date object represents a date (year, month and day) in an idealized calendar,
the current Gregorian calendar indefinitely extended in both directions.
Objects of this type are always naive.
"""
def __new__(cls, year: int, month: int, day: int) -> "date":
"""Creates a new date object.
:param int year: Year within range, MINYEAR <= year <= MAXYEAR
:param int month: Month within range, 1 <= month <= 12
:param int day: Day within range, 1 <= day <= number of days in the given month and year
"""
_check_date_fields(year, month, day)
self = object.__new__(cls)
self._year = year
self._month = month
self._day = day
self._hashcode = -1
return self
# Instance attributes (read-only)
@property
def year(self) -> int:
"""Between MINYEAR and MAXYEAR inclusive."""
return self._year
@property
def month(self) -> int:
"""Between 1 and 12 inclusive."""
return self._month
@property
def day(self) -> int:
"""Between 1 and the number of days in the given month of the given year."""
return self._day
# Class Methods
@classmethod
def fromtimestamp(cls, t: float) -> "date":
"""Return the local date corresponding to the POSIX timestamp,
such as is returned by time.time().
"""
tm_struct = _time.localtime(t)
return cls(tm_struct[0], tm_struct[1], tm_struct[2])
@classmethod
def fromordinal(cls, ordinal: int) -> "date":
"""Return the date corresponding to the proleptic Gregorian ordinal,
where January 1 of year 1 has ordinal 1.
"""
if not ordinal >= 1:
raise ValueError("ordinal must be >=1")
y, m, d = _ord2ymd(ordinal)
return cls(y, m, d)
@classmethod
def fromisoformat(cls, date_string: str) -> "date":
"""Return a date object constructed from an ISO date format.
Valid format is ``YYYY-MM-DD``
"""
match = _re.match(
r"([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$", date_string
)
if match:
y, m, d = int(match.group(1)), int(match.group(2)), int(match.group(3))
return cls(y, m, d)
raise ValueError(_INVALID_ISO_ERROR.format(date_string))
@classmethod
def today(cls) -> "date":
"""Return the current local date."""
return cls.fromtimestamp(_time.time())
# Instance Methods
def replace(
self,
year: Optional[int] = None,
month: Optional[int] = None,
day: Optional[int] = None,
):
"""Return a date with the same value, except for those parameters
given new values by whichever keyword arguments are specified.
If no keyword arguments are specified - values are obtained from
datetime object.
"""
raise NotImplementedError()
def timetuple(self) -> _time.struct_time:
"""Return a time.struct_time such as returned by time.localtime().
The hours, minutes and seconds are 0, and the DST flag is -1.
"""
return _build_struct_time(self._year, self._month, self._day, 0, 0, 0, -1)
def toordinal(self) -> int:
"""Return the proleptic Gregorian ordinal of the date, where January 1 of
year 1 has ordinal 1.
"""
return _ymd2ord(self._year, self._month, self._day)
def weekday(self) -> int:
"""Return the day of the week as an integer, where Monday is 0 and Sunday is 6."""
return (self.toordinal() + 6) % 7
# ISO date
def isoweekday(self) -> int:
"""Return the day of the week as an integer, where Monday is 1 and Sunday is 7."""
return self.toordinal() % 7 or 7
def isoformat(self) -> str:
"""Return a string representing the date in ISO 8601 format, YYYY-MM-DD:"""
return "%04d-%02d-%02d" % (self._year, self._month, self._day)
# For a date d, str(d) is equivalent to d.isoformat()
__str__ = isoformat
def __repr__(self) -> str:
"""Convert to formal string, for repr()."""
return "%s(%d, %d, %d)" % (
"datetime." + self.__class__.__name__,
self._year,
self._month,
self._day,
)
# Supported comparisons
def __eq__(self, other: "date") -> bool:
if isinstance(other, date):
return self._cmp(other) == 0
return NotImplemented
def __le__(self, other: "date") -> bool:
if isinstance(other, date):
return self._cmp(other) <= 0
return NotImplemented
def __lt__(self, other: "date") -> bool:
if isinstance(other, date):
return self._cmp(other) < 0
return NotImplemented
def __ge__(self, other: "date") -> bool:
if isinstance(other, date):
return self._cmp(other) >= 0
return NotImplemented
def __gt__(self, other: "date") -> bool:
if isinstance(other, date):
return self._cmp(other) > 0
return NotImplemented
def _cmp(self, other: "date") -> int:
assert isinstance(other, date)
y, m, d = self._year, self._month, self._day
y2, m2, d2 = other.year, other.month, other.day
return _cmp((y, m, d), (y2, m2, d2))
def __hash__(self) -> int:
if self._hashcode == -1:
self._hashcode = hash(self._getstate())
return self._hashcode
# Pickle support
def _getstate(self) -> Tuple[bytes]:
yhi, ylo = divmod(self._year, 256)
return (bytes([yhi, ylo, self._month, self._day]),)
def _setstate(self, string: bytes) -> None:
yhi, ylo, self._month, self._day = string
self._year = yhi * 256 + ylo
class timezone(tzinfo):
"""The timezone class is a subclass of tzinfo, each instance of which represents a
timezone defined by a fixed offset from UTC.
Objects of this class cannot be used to represent timezone information in the locations
where different offsets are used in different days of the year or where historical changes
have been made to civil time.
"""
# Sentinel value to disallow None
_Omitted = object()
def __new__(
cls, offset: timedelta, name: Union[str, object] = _Omitted
) -> "timezone":
if not isinstance(offset, timedelta):
raise TypeError("offset must be a timedelta")
if name is cls._Omitted:
if not offset:
return cls.utc
name = None
elif not isinstance(name, str):
raise TypeError("name must be a string")
if not cls.minoffset <= offset <= cls.maxoffset:
raise ValueError(
"offset must be a timedelta"
" strictly between -timedelta(hours=24) and"
" timedelta(hours=24)."
)
if offset.microseconds != 0 or offset.seconds % 60 != 0:
raise ValueError(
"offset must be a timedelta representing a whole number of minutes"
)
cls._offset = offset
cls._name = name
return cls._create(offset, name)
# pylint: disable=protected-access, bad-super-call
@classmethod
def _create(cls, offset: timedelta, name: Optional[str] = None) -> "timezone":
"""High-level creation for a timezone object."""
self = super(tzinfo, cls).__new__(cls)
self._offset = offset
self._name = name
return self
# Instance methods
def utcoffset(self, dt: Optional["datetime"]) -> timedelta:
if isinstance(dt, datetime) or dt is None:
return self._offset
raise TypeError("utcoffset() argument must be a datetime instance or None")
def tzname(self, dt: Optional["datetime"]) -> str:
if isinstance(dt, datetime) or dt is None:
if self._name is None:
return self._name_from_offset(self._offset)
return self._name
raise TypeError("tzname() argument must be a datetime instance or None")
# Comparison to other timezone objects
def __eq__(self, other: Any) -> bool:
if not isinstance(other, timezone):
return False
return self._offset == other._offset
def __hash__(self) -> int:
return hash(self._offset)
def __repr__(self) -> str:
"""Convert to formal string, for repr()."""
if self is self.utc:
return "datetime.timezone.utc"
if self._name is None:
return "%s(%r)" % ("datetime." + self.__class__.__name__, self._offset)
return "%s(%r, %r)" % (
"datetime." + self.__class__.__name__,
self._offset,
self._name,
)
def __str__(self) -> str:
return self.tzname(None)
@staticmethod
def _name_from_offset(delta: timedelta) -> str:
if delta < timedelta(0):
sign = "-"
delta = -delta
else:
sign = "+"
hours, rest = divmod(delta, timedelta(hours=1))
minutes = rest // timedelta(minutes=1)
return "UTC{}{:02d}:{:02d}".format(sign, hours, minutes)
maxoffset = timedelta(hours=23, minutes=59)
minoffset = -maxoffset
class time:
"""A time object represents a (local) time of day, independent of
any particular day, and subject to adjustment via a tzinfo object.
"""
# pylint: disable=redefined-outer-name
def __new__(
cls,
hour: int = 0,
minute: int = 0,
second: int = 0,
microsecond: int = 0,
tzinfo: Optional[tzinfo] = None,
*,
fold: int = 0,
) -> "time":
_check_time_fields(hour, minute, second, microsecond, fold)
_check_tzinfo_arg(tzinfo)
self = object.__new__(cls)
self._hour = hour
self._minute = minute
self._second = second
self._microsecond = microsecond
self._tzinfo = tzinfo
self._fold = fold
self._hashcode = -1
return self
# Instance attributes (read-only)
@property
def hour(self) -> int:
"""In range(24)."""
return self._hour
@property
def minute(self) -> int:
"""In range(60)."""
return self._minute
@property
def second(self) -> int:
"""In range(60)."""
return self._second
@property
def microsecond(self) -> int:
"""In range(1000000)."""
return self._microsecond
@property
def fold(self) -> int:
"""Fold."""
return self._fold
@property
def tzinfo(self) -> Optional[tzinfo]:
"""The object passed as the tzinfo argument to
the time constructor, or None if none was passed.
"""
return self._tzinfo
@staticmethod
def _parse_iso_string(string_to_parse: str, segments: Sequence[str]) -> List[int]:
results = []
remaining_string = string_to_parse
for regex in segments:
match = _re.match(regex, remaining_string)
if match:
for grp in range(regex.count("(")):
results.append(int(match.group(grp + 1)))
remaining_string = remaining_string[len(match.group(0)) :]
elif remaining_string: # Only raise an error if we're not done yet
raise ValueError()
if remaining_string:
raise ValueError()
return results
# pylint: disable=too-many-locals
@classmethod
def fromisoformat(cls, time_string: str) -> "time":
"""Return a time object constructed from an ISO date format.
Valid format is ``HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]``
"""
if time_string[-1] == "Z":
time_string = f"{time_string[:-1]}+00:00"
# Store the original string in an error message
original_string = time_string