Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 35.3k
Expand file tree
/
Copy path_zoneinfo.py
More file actions
Latest commit
779 lines (623 loc) · 24.5 KB
/
Copy path_zoneinfo.py
File metadata and controls
779 lines (623 loc) · 24.5 KB
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
importbisect
importcalendar
importcollections
importfunctools
importre
importweakref
fromdatetimeimportdatetime, timedelta, tzinfo
from . import_common, _tzpath
EPOCH=datetime(1970, 1, 1)
EPOCHORDINAL=datetime(1970, 1, 1).toordinal()
# It is relatively expensive to construct new timedelta objects, and in most
# cases we're looking at the same deltas, like integer numbers of hours, etc.
# To improve speed and memory use, we'll keep a dictionary with references
# to the ones we've already used so far.
#
# Loading every time zone in the 2020a version of the time zone database
# requires 447 timedeltas, which requires approximately the amount of space
# that ZoneInfo("America/New_York") with 236 transitions takes up, so we will
# set the cache size to 512 so that in the common case we always get cache
# hits, but specifically crafted ZoneInfo objects don't leak arbitrary amounts
# of memory.
@functools.lru_cache(maxsize=512)
def_load_timedelta(seconds):
returntimedelta(seconds=seconds)
classZoneInfo(tzinfo):
_strong_cache_size=8
_strong_cache=collections.OrderedDict()
_weak_cache=weakref.WeakValueDictionary()
__module__="zoneinfo"
def__init_subclass__(cls):
cls._strong_cache=collections.OrderedDict()
cls._weak_cache=weakref.WeakValueDictionary()
def__new__(cls, key):
instance=cls._weak_cache.get(key, None)
ifinstanceisNone:
instance=cls._weak_cache.setdefault(key, cls._new_instance(key))
instance._from_cache=True
# Update the "strong" cache
cls._strong_cache[key] =cls._strong_cache.pop(key, instance)
iflen(cls._strong_cache) >cls._strong_cache_size:
try:
cls._strong_cache.popitem(last=False)
exceptKeyError:
# another thread may have already emptied the cache
pass
returninstance
@classmethod
defno_cache(cls, key):
obj=cls._new_instance(key)
obj._from_cache=False
returnobj
@classmethod
def_new_instance(cls, key):
obj=super().__new__(cls)
obj._key=key
obj._file_path=obj._find_tzfile(key)
ifobj._file_pathisnotNone:
file_obj=open(obj._file_path, "rb")
else:
file_obj=_common.load_tzdata(key)
withfile_objasf:
obj._load_file(f)
returnobj
@classmethod
deffrom_file(cls, file_obj, /, key=None):
obj=super().__new__(cls)
obj._key=key
obj._file_path=None
obj._load_file(file_obj)
obj._file_repr=repr(file_obj)
# Disable pickling for objects created from files
obj.__reduce__=obj._file_reduce
returnobj
@classmethod
defclear_cache(cls, *, only_keys=None):
ifonly_keysisnotNone:
forkeyinonly_keys:
cls._weak_cache.pop(key, None)
cls._strong_cache.pop(key, None)
else:
cls._weak_cache.clear()
cls._strong_cache.clear()
@property
defkey(self):
returnself._key
defutcoffset(self, dt):
returnself._find_trans(dt).utcoff
defdst(self, dt):
returnself._find_trans(dt).dstoff
deftzname(self, dt):
returnself._find_trans(dt).tzname
deffromutc(self, dt):
"""Convert from datetime in UTC to datetime in local time"""
ifnotisinstance(dt, datetime):
raiseTypeError("fromutc() requires a datetime argument")
ifdt.tzinfoisnotself:
raiseValueError("dt.tzinfo is not self")
timestamp=self._get_local_timestamp(dt)
num_trans=len(self._trans_utc)
ifnum_trans>=1andtimestamp<self._trans_utc[0]:
tti=self._tti_before
fold=0
elif (
num_trans==0ortimestamp>self._trans_utc[-1]
) andnotisinstance(self._tz_after, _ttinfo):
tti, fold=self._tz_after.get_trans_info_fromutc(
timestamp, dt.year
)
elifnum_trans==0:
tti=self._tz_after
fold=0
else:
idx=bisect.bisect_right(self._trans_utc, timestamp)
ifnum_trans>1andtimestamp>=self._trans_utc[1]:
tti_prev, tti=self._ttinfos[idx-2 : idx]
eliftimestamp>self._trans_utc[-1]:
tti_prev=self._ttinfos[-1]
tti=self._tz_after
else:
tti_prev=self._tti_before
tti=self._ttinfos[0]
# Detect fold
shift=tti_prev.utcoff-tti.utcoff
fold=shift.total_seconds() >timestamp-self._trans_utc[idx-1]
dt+=tti.utcoff
iffold:
returndt.replace(fold=1)
else:
returndt
def_find_trans(self, dt):
ifdtisNone:
ifself._fixed_offset:
returnself._tz_after
else:
return_NO_TTINFO
ts=self._get_local_timestamp(dt)
lt=self._trans_local[dt.fold]
num_trans=len(lt)
ifnum_transandts<lt[0]:
returnself._tti_before
elifnotnum_transorts>lt[-1]:
ifisinstance(self._tz_after, _TZStr):
returnself._tz_after.get_trans_info(ts, dt.year, dt.fold)
else:
returnself._tz_after
else:
# idx is the transition that occurs after this timestamp, so we
# subtract off 1 to get the current ttinfo
idx=bisect.bisect_right(lt, ts) -1
assertidx>=0
returnself._ttinfos[idx]
def_get_local_timestamp(self, dt):
return (
(dt.toordinal() -EPOCHORDINAL) *86400
+dt.hour*3600
+dt.minute*60
+dt.second
)
def__str__(self):
ifself._keyisnotNone:
returnf"{self._key}"
else:
returnrepr(self)
def__repr__(self):
ifself._keyisnotNone:
returnf"{self.__class__.__name__}(key={self._key!r})"
else:
returnf"{self.__class__.__name__}.from_file({self._file_repr})"
def__reduce__(self):
return (self.__class__._unpickle, (self._key, self._from_cache))
def_file_reduce(self):
importpickle
raisepickle.PicklingError(
"Cannot pickle a ZoneInfo file created from a file stream."
)
@classmethod
def_unpickle(cls, key, from_cache, /):
iffrom_cache:
returncls(key)
else:
returncls.no_cache(key)
def_find_tzfile(self, key):
return_tzpath.find_tzfile(key)
def_load_file(self, fobj):
# Retrieve all the data as it exists in the zoneinfo file
trans_idx, trans_utc, utcoff, isdst, abbr, tz_str=_common.load_data(
fobj
)
# Infer the DST offsets (needed for .dst()) from the data
dstoff=self._utcoff_to_dstoff(trans_idx, utcoff, isdst)
# Convert all the transition times (UTC) into "seconds since 1970-01-01 local time"
trans_local=self._ts_to_local(trans_idx, trans_utc, utcoff)
# Construct `_ttinfo` objects for each transition in the file
_ttinfo_list= [
_ttinfo(
_load_timedelta(utcoffset), _load_timedelta(dstoffset), tzname
)
forutcoffset, dstoffset, tznameinzip(utcoff, dstoff, abbr)
]
self._trans_utc=trans_utc
self._trans_local=trans_local
self._ttinfos= [_ttinfo_list[idx] foridxintrans_idx]
# Find the first non-DST transition
foriinrange(len(isdst)):
ifnotisdst[i]:
self._tti_before=_ttinfo_list[i]
break
else:
ifself._ttinfos:
self._tti_before=self._ttinfos[0]
else:
self._tti_before=None
# Set the "fallback" time zone
iftz_strisnotNoneandtz_str!=b"":
self._tz_after=_parse_tz_str(tz_str.decode())
else:
ifnotself._ttinfosandnot_ttinfo_list:
raiseValueError("No time zone information found.")
ifself._ttinfos:
self._tz_after=self._ttinfos[-1]
else:
self._tz_after=_ttinfo_list[-1]
# Determine if this is a "fixed offset" zone, meaning that the output
# of the utcoffset, dst and tzname functions does not depend on the
# specific datetime passed.
#
# We make three simplifying assumptions here:
#
# 1. If _tz_after is not a _ttinfo, it has transitions that might
# actually occur (it is possible to construct TZ strings that
# specify STD and DST but no transitions ever occur, such as
# AAA0BBB,0/0,J365/25).
# 2. If _ttinfo_list contains more than one _ttinfo object, the objects
# represent different offsets.
# 3. _ttinfo_list contains no unused _ttinfos (in which case an
# otherwise fixed-offset zone with extra _ttinfos defined may
# appear to *not* be a fixed offset zone).
#
# Violations to these assumptions would be fairly exotic, and exotic
# zones should almost certainly not be used with datetime.time (the
# only thing that would be affected by this).
iflen(_ttinfo_list) >1ornotisinstance(self._tz_after, _ttinfo):
self._fixed_offset=False
elifnot_ttinfo_list:
self._fixed_offset=True
else:
self._fixed_offset=_ttinfo_list[0] ==self._tz_after
@staticmethod
def_utcoff_to_dstoff(trans_idx, utcoffsets, isdsts):
# Now we must transform our ttis and abbrs into `_ttinfo` objects,
# but there is an issue: .dst() must return a timedelta with the
# difference between utcoffset() and the "standard" offset, but
# the "base offset" and "DST offset" are not encoded in the file;
# we can infer what they are from the isdst flag, but it is not
# sufficient to just look at the last standard offset, because
# occasionally countries will shift both DST offset and base offset.
typecnt=len(isdsts)
dstoffs= [0] *typecnt# Provisionally assign all to 0.
dst_cnt=sum(isdsts)
dst_found=0
foriinrange(1, len(trans_idx)):
ifdst_cnt==dst_found:
break
idx=trans_idx[i]
dst=isdsts[idx]
# We're only going to look at daylight saving time
ifnotdst:
continue
# Skip any offsets that have already been assigned
ifdstoffs[idx] !=0:
continue
dstoff=0
utcoff=utcoffsets[idx]
comp_idx=trans_idx[i-1]
ifnotisdsts[comp_idx]:
dstoff=utcoff-utcoffsets[comp_idx]
ifnotdstoffandidx< (typecnt-1) andi+1<len(trans_idx):
comp_idx=trans_idx[i+1]
# If the following transition is also DST and we couldn't
# find the DST offset by this point, we're going to have to
# skip it and hope this transition gets assigned later
ifisdsts[comp_idx]:
continue
dstoff=utcoff-utcoffsets[comp_idx]
ifdstoff:
dst_found+=1
dstoffs[idx] =dstoff
else:
# If we didn't find a valid value for a given index, we'll end up
# with dstoff = 0 for something where `isdst=1`. This is obviously
# wrong - one hour will be a much better guess than 0
foridxinrange(typecnt):
ifnotdstoffs[idx] andisdsts[idx]:
dstoffs[idx] =3600
returndstoffs
@staticmethod
def_ts_to_local(trans_idx, trans_list_utc, utcoffsets):
"""Generate number of seconds since 1970 *in the local time*.
This is necessary to easily find the transition times in local time"""
ifnottrans_list_utc:
return [[], []]
# Start with the timestamps and modify in-place
trans_list_wall= [list(trans_list_utc), list(trans_list_utc)]
iflen(utcoffsets) >1:
offset_0=utcoffsets[0]
offset_1=utcoffsets[trans_idx[0]]
ifoffset_1>offset_0:
offset_1, offset_0=offset_0, offset_1
else:
offset_0=offset_1=utcoffsets[0]
trans_list_wall[0][0] +=offset_0
trans_list_wall[1][0] +=offset_1
foriinrange(1, len(trans_idx)):
offset_0=utcoffsets[trans_idx[i-1]]
offset_1=utcoffsets[trans_idx[i]]
ifoffset_1>offset_0:
offset_1, offset_0=offset_0, offset_1
trans_list_wall[0][i] +=offset_0
trans_list_wall[1][i] +=offset_1
returntrans_list_wall
class_ttinfo:
__slots__= ["utcoff", "dstoff", "tzname"]
def__init__(self, utcoff, dstoff, tzname):
self.utcoff=utcoff
self.dstoff=dstoff
self.tzname=tzname
def__eq__(self, other):
return (
self.utcoff==other.utcoff
andself.dstoff==other.dstoff
andself.tzname==other.tzname
)
def__repr__(self): # pragma: nocover
return (
f"{self.__class__.__name__}"
+f"({self.utcoff}, {self.dstoff}, {self.tzname})"
)
_NO_TTINFO=_ttinfo(None, None, None)
class_TZStr:
__slots__= (
"std",
"dst",
"start",
"end",
"get_trans_info",
"get_trans_info_fromutc",
"dst_diff",
)
def__init__(
self, std_abbr, std_offset, dst_abbr, dst_offset, start=None, end=None
):
self.dst_diff=dst_offset-std_offset
std_offset=_load_timedelta(std_offset)
self.std=_ttinfo(
utcoff=std_offset, dstoff=_load_timedelta(0), tzname=std_abbr
)
self.start=start
self.end=end
dst_offset=_load_timedelta(dst_offset)
delta=_load_timedelta(self.dst_diff)
self.dst=_ttinfo(utcoff=dst_offset, dstoff=delta, tzname=dst_abbr)
# These are assertions because the constructor should only be called
# by functions that would fail before passing start or end
assertstartisnotNone, "No transition start specified"
assertendisnotNone, "No transition end specified"
self.get_trans_info=self._get_trans_info
self.get_trans_info_fromutc=self._get_trans_info_fromutc
deftransitions(self, year):
start=self.start.year_to_epoch(year)
end=self.end.year_to_epoch(year)
returnstart, end
def_get_trans_info(self, ts, year, fold):
"""Get the information about the current transition - tti"""
start, end=self.transitions(year)
# With fold = 0, the period (denominated in local time) with the
# smaller offset starts at the end of the gap and ends at the end of
# the fold; with fold = 1, it runs from the start of the gap to the
# beginning of the fold.
#
# So in order to determine the DST boundaries we need to know both
# the fold and whether DST is positive or negative (rare), and it
# turns out that this boils down to fold XOR is_positive.
iffold== (self.dst_diff>=0):
end-=self.dst_diff
else:
start+=self.dst_diff
ifstart<end:
isdst=start<=ts<end
else:
isdst=not (end<=ts<start)
returnself.dstifisdstelseself.std
def_get_trans_info_fromutc(self, ts, year):
start, end=self.transitions(year)
start-=self.std.utcoff.total_seconds()
end-=self.dst.utcoff.total_seconds()
ifstart<end:
isdst=start<=ts<end
else:
isdst=not (end<=ts<start)
# For positive DST, the ambiguous period is one dst_diff after the end
# of DST; for negative DST, the ambiguous period is one dst_diff before
# the start of DST.
ifself.dst_diff>0:
ambig_start=end
ambig_end=end+self.dst_diff
else:
ambig_start=start
ambig_end=start-self.dst_diff
fold=ambig_start<=ts<ambig_end
return (self.dstifisdstelseself.std, fold)
def_post_epoch_days_before_year(year):
"""Get the number of days between 1970-01-01 and YEAR-01-01"""
y=year-1
returny*365+y//4-y//100+y//400-EPOCHORDINAL
class_DayOffset:
__slots__= ["d", "julian", "hour", "minute", "second"]
def__init__(self, d, julian, hour=2, minute=0, second=0):
min_day=0+julian# convert bool to int
ifnotmin_day<=d<=365:
raiseValueError(f"d must be in [{min_day}, 365], not: {d}")
self.d=d
self.julian=julian
self.hour=hour
self.minute=minute
self.second=second
defyear_to_epoch(self, year):
days_before_year=_post_epoch_days_before_year(year)
d=self.d
ifself.julianandd>=59andcalendar.isleap(year):
d+=1
epoch= (days_before_year+d) *86400
epoch+=self.hour*3600+self.minute*60+self.second
returnepoch
class_CalendarOffset:
__slots__= ["m", "w", "d", "hour", "minute", "second"]
_DAYS_BEFORE_MONTH= (
-1,
0,
31,
59,
90,
120,
151,
181,
212,
243,
273,
304,
334,
)
def__init__(self, m, w, d, hour=2, minute=0, second=0):
ifnot1<=m<=12:
raiseValueError("m must be in [1, 12]")
ifnot1<=w<=5:
raiseValueError("w must be in [1, 5]")
ifnot0<=d<=6:
raiseValueError("d must be in [0, 6]")
self.m=m
self.w=w
self.d=d
self.hour=hour
self.minute=minute
self.second=second
@classmethod
def_ymd2ord(cls, year, month, day):
return (
_post_epoch_days_before_year(year)
+cls._DAYS_BEFORE_MONTH[month]
+ (month>2andcalendar.isleap(year))
+day
)
# TODO: These are not actually epoch dates as they are expressed in local time
defyear_to_epoch(self, year):
"""Calculates the datetime of the occurrence from the year"""
# We know year and month, we need to convert w, d into day of month
#
# Week 1 is the first week in which day `d` (where 0 = Sunday) appears.
# Week 5 represents the last occurrence of day `d`, so we need to know
# the range of the month.
first_day, days_in_month=calendar.monthrange(year, self.m)
# This equation seems magical, so I'll break it down:
# 1. calendar says 0 = Monday, POSIX says 0 = Sunday
# so we need first_day + 1 to get 1 = Monday -> 7 = Sunday,
# which is still equivalent because this math is mod 7
# 2. Get first day - desired day mod 7: -1 % 7 = 6, so we don't need
# to do anything to adjust negative numbers.
# 3. Add 1 because month days are a 1-based index.
month_day= (self.d- (first_day+1)) %7+1
# Now use a 0-based index version of `w` to calculate the w-th
# occurrence of `d`
month_day+= (self.w-1) *7
# month_day will only be > days_in_month if w was 5, and `w` means
# "last occurrence of `d`", so now we just check if we over-shot the
# end of the month and if so knock off 1 week.
ifmonth_day>days_in_month:
month_day-=7
ordinal=self._ymd2ord(year, self.m, month_day)
epoch=ordinal*86400
epoch+=self.hour*3600+self.minute*60+self.second
returnepoch
def_parse_tz_str(tz_str):
# The tz string has the format:
#
# std[offset[dst[offset],start[/time],end[/time]]]
#
# std and dst must be 3 or more characters long and must not contain
# a leading colon, embedded digits, commas, nor a plus or minus signs;
# The spaces between "std" and "offset" are only for display and are
# not actually present in the string.
#
# The format of the offset is ``[+|-]hh[:mm[:ss]]``
offset_str, *start_end_str=tz_str.split(",", 1)
parser_re=re.compile(
r"""
(?P<std>[a-zA-Z]+|<[a-zA-Z0-9+-]+>)
(?:
(?P<stdoff>[+-]?\d{1,3}(?::\d{2}(?::\d{2})?)?)
(?:
(?P<dst>[a-zA-Z]+|<[a-zA-Z0-9+-]+>)
(?P<dstoff>[+-]?\d{1,3}(?::\d{2}(?::\d{2})?)?)?
)? # dst
)? # stdoff
""",
re.ASCII|re.VERBOSE
)
m=parser_re.fullmatch(offset_str)
ifmisNone:
raiseValueError(f"{tz_str} is not a valid TZ string")
std_abbr=m.group("std")
dst_abbr=m.group("dst")
dst_offset=None
std_abbr=std_abbr.strip("<>")
ifdst_abbr:
dst_abbr=dst_abbr.strip("<>")
ifstd_offset:=m.group("stdoff"):
try:
std_offset=_parse_tz_delta(std_offset)
exceptValueErrorase:
raiseValueError(f"Invalid STD offset in {tz_str}") frome
else:
# The STD offset is required
raiseValueError(f"Invalid STD offset in {tz_str}")
ifdst_abbrisnotNone:
ifdst_offset:=m.group("dstoff"):
try:
dst_offset=_parse_tz_delta(dst_offset)
exceptValueErrorase:
raiseValueError(f"Invalid DST offset in {tz_str}") frome
else:
dst_offset=std_offset+3600
ifnotstart_end_str:
raiseValueError(f"Missing transition rules: {tz_str}")
start_end_strs=start_end_str[0].split(",", 1)
try:
start, end= (_parse_dst_start_end(x) forxinstart_end_strs)
exceptValueErrorase:
raiseValueError(f"Invalid TZ string: {tz_str}") frome
return_TZStr(std_abbr, std_offset, dst_abbr, dst_offset, start, end)
elifstart_end_str:
raiseValueError(f"Transition rule present without DST: {tz_str}")
else:
# This is a static ttinfo, don't return _TZStr
return_ttinfo(
_load_timedelta(std_offset), _load_timedelta(0), std_abbr
)
def_parse_dst_start_end(dststr):
date, *time=dststr.split("/", 1)
type=date[:1]
iftype=="M":
n_is_julian=False
m=re.fullmatch(r"M(\d{1,2})\.(\d)\.(\d)", date, re.ASCII)
ifmisNone:
raiseValueError(f"Invalid dst start/end date: {dststr}")
date_offset=tuple(map(int, m.groups()))
offset=_CalendarOffset(*date_offset)
else:
iftype=="J":
n_is_julian=True
date=date[1:]
else:
n_is_julian=False
ifre.fullmatch(r"\d{1,3}", date, re.ASCII) isNone:
raiseValueError(f"Invalid dst start/end date: {dststr}")
doy=int(date)
offset=_DayOffset(doy, n_is_julian)
iftime:
offset.hour, offset.minute, offset.second=_parse_transition_time(time[0])
returnoffset
def_parse_transition_time(time_str):
match=re.fullmatch(
r"(?P<sign>[+-])?(?P<h>\d{1,3})(:(?P<m>\d{2})(:(?P<s>\d{2}))?)?",
time_str,
re.ASCII
)
ifmatchisNone:
raiseValueError(f"Invalid time: {time_str}")
h, m, s= (int(vor0) forvinmatch.group("h", "m", "s"))
ifh>167:
raiseValueError(
f"Hour must be in [0, 167]: {time_str}"
)
ifmatch.group("sign") =="-":
h, m, s=-h, -m, -s
returnh, m, s
def_parse_tz_delta(tz_delta):
match=re.fullmatch(
r"(?P<sign>[+-])?(?P<h>\d{1,3})(:(?P<m>\d{2})(:(?P<s>\d{2}))?)?",
tz_delta,
re.ASCII
)
# Anything passed to this function should already have hit an equivalent
# regular expression to find the section to parse.
assertmatchisnotNone, tz_delta
h, m, s= (int(vor0) forvinmatch.group("h", "m", "s"))
total=h*3600+m*60+s
ifh>24:
raiseValueError(
f"Offset hours must be in [0, 24]: {tz_delta}"
)
# Yes, +5 maps to an offset of -5h
ifmatch.group("sign") !="-":
total=-total
returntotal