codekingpro/portable-devtools
114k
1"""Strptime-related classes and functions.2 3CLASSES:4 LocaleTime -- Discovers and stores locale-specific time information5 TimeRE -- Creates regexes for pattern matching a string of text containing6 time information7 8FUNCTIONS:9 _getlang -- Figure out what language is being used for the locale10 strptime -- Calculates the time struct represented by the passed-in string11 12"""13import os14import time15import locale16import calendar17import re18from re import compile as re_compile19from re import sub as re_sub20from re import IGNORECASE21from re import escape as re_escape22from datetime import (date as datetime_date,23 timedelta as datetime_timedelta,24 timezone as datetime_timezone)25from _thread import allocate_lock as _thread_allocate_lock26 27__all__ = []28 29def _getlang():30 # Figure out what the current language is set to.31 return locale.getlocale(locale.LC_TIME)32 33def _findall(haystack, needle):34 # Find all positions of needle in haystack.35 if not needle:36 return37 i = 038 while True:39 i = haystack.find(needle, i)40 if i < 0:41 break42 yield i43 i += len(needle)44 45def _fixmonths(months):46 yield from months47 # The lower case of 'İ' ('\u0130') is 'i\u0307'.48 # The re module only supports 1-to-1 character matching in49 # case-insensitive mode.50 for s in months:51 if 'i\u0307' in s:52 yield s.replace('i\u0307', '\u0130')53 54lzh_TW_alt_digits = (55 # 〇:一:二:三:四:五:六:七:八:九56 '\u3007', '\u4e00', '\u4e8c', '\u4e09', '\u56db',57 '\u4e94', '\u516d', '\u4e03', '\u516b', '\u4e5d',58 # 十:十一:十二:十三:十四:十五:十六:十七:十八:十九59 '\u5341', '\u5341\u4e00', '\u5341\u4e8c', '\u5341\u4e09', '\u5341\u56db',60 '\u5341\u4e94', '\u5341\u516d', '\u5341\u4e03', '\u5341\u516b', '\u5341\u4e5d',61 # 廿:廿一:廿二:廿三:廿四:廿五:廿六:廿七:廿八:廿九62 '\u5eff', '\u5eff\u4e00', '\u5eff\u4e8c', '\u5eff\u4e09', '\u5eff\u56db',63 '\u5eff\u4e94', '\u5eff\u516d', '\u5eff\u4e03', '\u5eff\u516b', '\u5eff\u4e5d',64 # 卅:卅一65 '\u5345', '\u5345\u4e00')66 67 68class LocaleTime(object):69 """Stores and handles locale-specific information related to time.70 71 ATTRIBUTES:72 f_weekday -- full weekday names (7-item list)73 a_weekday -- abbreviated weekday names (7-item list)74 f_month -- full month names (13-item list; dummy value in [0], which75 is added by code)76 a_month -- abbreviated month names (13-item list, dummy value in77 [0], which is added by code)78 am_pm -- AM/PM representation (2-item list)79 LC_date_time -- format string for date/time representation (string)80 LC_date -- format string for date representation (string)81 LC_time -- format string for time representation (string)82 timezone -- daylight- and non-daylight-savings timezone representation83 (2-item list of sets)84 lang -- Language used by instance (2-item tuple)85 """86 87 def __init__(self):88 """Set all attributes.89 90 Order of methods called matters for dependency reasons.91 92 The locale language is set at the offset and then checked again before93 exiting. This is to make sure that the attributes were not set with a94 mix of information from more than one locale. This would most likely95 happen when using threads where one thread calls a locale-dependent96 function while another thread changes the locale while the function in97 the other thread is still running. Proper coding would call for98 locks to prevent changing the locale while locale-dependent code is99 running. The check here is done in case someone does not think about100 doing this.101 102 Only other possible issue is if someone changed the timezone and did103 not call tz.tzset . That is an issue for the programmer, though,104 since changing the timezone is worthless without that call.105 106 """107 self.lang = _getlang()108 self.__calc_weekday()109 self.__calc_month()110 self.__calc_am_pm()111 self.__calc_alt_digits()112 self.__calc_timezone()113 self.__calc_date_time()114 if _getlang() != self.lang:115 raise ValueError("locale changed during initialization")116 if time.tzname != self.tzname or time.daylight != self.daylight:117 raise ValueError("timezone changed during initialization")118 119 def __calc_weekday(self):120 # Set self.a_weekday and self.f_weekday using the calendar121 # module.122 a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]123 f_weekday = [calendar.day_name[i].lower() for i in range(7)]124 self.a_weekday = a_weekday125 self.f_weekday = f_weekday126 127 def __calc_month(self):128 # Set self.f_month and self.a_month using the calendar module.129 a_month = [calendar.month_abbr[i].lower() for i in range(13)]130 f_month = [calendar.month_name[i].lower() for i in range(13)]131 self.a_month = a_month132 self.f_month = f_month133 134 def __calc_am_pm(self):135 # Set self.am_pm by using time.strftime().136 137 # The magic date (1999,3,17,hour,44,55,2,76,0) is not really that138 # magical; just happened to have used it everywhere else where a139 # static date was needed.140 am_pm = []141 for hour in (1, 22):142 time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0))143 # br_FR has AM/PM info (' ',' ').144 am_pm.append(time.strftime("%p", time_tuple).lower().strip())145 self.am_pm = am_pm146 147 def __calc_alt_digits(self):148 # Set self.LC_alt_digits by using time.strftime().149 150 # The magic data should contain all decimal digits.151 time_tuple = time.struct_time((1998, 1, 27, 10, 43, 56, 1, 27, 0))152 s = time.strftime("%x%X", time_tuple)153 if s.isascii():154 # Fast path -- all digits are ASCII.155 self.LC_alt_digits = ()156 return157 158 digits = ''.join(sorted(set(re.findall(r'\d', s))))159 if len(digits) == 10 and ord(digits[-1]) == ord(digits[0]) + 9:160 # All 10 decimal digits from the same set.161 if digits.isascii():162 # All digits are ASCII.163 self.LC_alt_digits = ()164 return165 166 self.LC_alt_digits = [a + b for a in digits for b in digits]167 # Test whether the numbers contain leading zero.168 time_tuple2 = time.struct_time((2000, 1, 1, 1, 1, 1, 5, 1, 0))169 if self.LC_alt_digits[1] not in time.strftime("%x %X", time_tuple2):170 self.LC_alt_digits[:10] = digits171 return172 173 # Either non-Gregorian calendar or non-decimal numbers.174 if {'\u4e00', '\u4e03', '\u4e5d', '\u5341', '\u5eff'}.issubset(s):175 # lzh_TW176 self.LC_alt_digits = lzh_TW_alt_digits177 return178 179 self.LC_alt_digits = None180 181 def __calc_date_time(self):182 # Set self.LC_date_time, self.LC_date, self.LC_time and183 # self.LC_time_ampm by using time.strftime().184 185 # Use (1999,3,17,22,44,55,2,76,0) for magic date because the amount of186 # overloaded numbers is minimized. The order in which searches for187 # values within the format string is very important; it eliminates188 # possible ambiguity for what something represents.189 time_tuple = time.struct_time((1999,3,17,22,44,55,2,76,0))190 time_tuple2 = time.struct_time((1999,1,3,1,1,1,6,3,0))191 replacement_pairs = []192 193 # Non-ASCII digits194 if self.LC_alt_digits or self.LC_alt_digits is None:195 for n, d in [(19, '%OC'), (99, '%Oy'), (22, '%OH'),196 (44, '%OM'), (55, '%OS'), (17, '%Od'),197 (3, '%Om'), (2, '%Ow'), (10, '%OI')]:198 if self.LC_alt_digits is None:199 s = chr(0x660 + n // 10) + chr(0x660 + n % 10)200 replacement_pairs.append((s, d))201 if n < 10:202 replacement_pairs.append((s[1], d))203 elif len(self.LC_alt_digits) > n:204 replacement_pairs.append((self.LC_alt_digits[n], d))205 else:206 replacement_pairs.append((time.strftime(d, time_tuple), d))207 replacement_pairs += [208 ('1999', '%Y'), ('99', '%y'), ('22', '%H'),209 ('44', '%M'), ('55', '%S'), ('76', '%j'),210 ('17', '%d'), ('03', '%m'), ('3', '%m'),211 # '3' needed for when no leading zero.212 ('2', '%w'), ('10', '%I'),213 ]214 215 date_time = []216 for directive in ('%c', '%x', '%X', '%r'):217 current_format = time.strftime(directive, time_tuple).lower()218 current_format = current_format.replace('%', '%%')219 # The month and the day of the week formats are treated specially220 # because of a possible ambiguity in some locales where the full221 # and abbreviated names are equal or names of different types222 # are equal. See doc of __find_month_format for more details.223 lst, fmt = self.__find_weekday_format(directive)224 if lst:225 current_format = current_format.replace(lst[2], fmt, 1)226 lst, fmt = self.__find_month_format(directive)227 if lst:228 current_format = current_format.replace(lst[3], fmt, 1)229 if self.am_pm[1]:230 # Must deal with possible lack of locale info231 # manifesting itself as the empty string (e.g., Swedish's232 # lack of AM/PM info) or a platform returning a tuple of empty233 # strings (e.g., MacOS 9 having timezone as ('','')).234 current_format = current_format.replace(self.am_pm[1], '%p')235 for tz_values in self.timezone:236 for tz in tz_values:237 if tz:238 current_format = current_format.replace(tz, "%Z")239 # Transform all non-ASCII digits to digits in range U+0660 to U+0669.240 if not current_format.isascii() and self.LC_alt_digits is None:241 current_format = re_sub(r'\d(?<![0-9])',242 lambda m: chr(0x0660 + int(m[0])),243 current_format)244 for old, new in replacement_pairs:245 current_format = current_format.replace(old, new)246 # If %W is used, then Sunday, 2005-01-03 will fall on week 0 since247 # 2005-01-03 occurs before the first Monday of the year. Otherwise248 # %U is used.249 if '00' in time.strftime(directive, time_tuple2):250 U_W = '%W'251 else:252 U_W = '%U'253 current_format = current_format.replace('11', U_W)254 date_time.append(current_format)255 self.LC_date_time = date_time[0]256 self.LC_date = date_time[1]257 self.LC_time = date_time[2]258 self.LC_time_ampm = date_time[3]259 260 def __find_month_format(self, directive):261 """Find the month format appropriate for the current locale.262 263 In some locales (for example French and Hebrew), the default month264 used in __calc_date_time has the same name in full and abbreviated265 form. Also, the month name can by accident match other part of the266 representation: the day of the week name (for example in Morisyen)267 or the month number (for example in Japanese). Thus, cycle months268 of the year and find all positions that match the month name for269 each month, If no common positions are found, the representation270 does not use the month name.271 """272 full_indices = abbr_indices = None273 for m in range(1, 13):274 time_tuple = time.struct_time((1999, m, 17, 22, 44, 55, 2, 76, 0))275 datetime = time.strftime(directive, time_tuple).lower()276 indices = set(_findall(datetime, self.f_month[m]))277 if full_indices is None:278 full_indices = indices279 else:280 full_indices &= indices281 indices = set(_findall(datetime, self.a_month[m]))282 if abbr_indices is None:283 abbr_indices = set(indices)284 else:285 abbr_indices &= indices286 if not full_indices and not abbr_indices:287 return None, None288 if full_indices:289 return self.f_month, '%B'290 if abbr_indices:291 return self.a_month, '%b'292 return None, None293 294 def __find_weekday_format(self, directive):295 """Find the day of the week format appropriate for the current locale.296 297 Similar to __find_month_format().298 """299 full_indices = abbr_indices = None300 for wd in range(7):301 time_tuple = time.struct_time((1999, 3, 17, 22, 44, 55, wd, 76, 0))302 datetime = time.strftime(directive, time_tuple).lower()303 indices = set(_findall(datetime, self.f_weekday[wd]))304 if full_indices is None:305 full_indices = indices306 else:307 full_indices &= indices308 if self.f_weekday[wd] != self.a_weekday[wd]:309 indices = set(_findall(datetime, self.a_weekday[wd]))310 if abbr_indices is None:311 abbr_indices = set(indices)312 else:313 abbr_indices &= indices314 if not full_indices and not abbr_indices:315 return None, None316 if full_indices:317 return self.f_weekday, '%A'318 if abbr_indices:319 return self.a_weekday, '%a'320 return None, None321 322 def __calc_timezone(self):323 # Set self.timezone by using time.tzname.324 # Do not worry about possibility of time.tzname[0] == time.tzname[1]325 # and time.daylight; handle that in strptime.326 try:327 time.tzset()328 except AttributeError:329 pass330 self.tzname = time.tzname331 self.daylight = time.daylight332 no_saving = frozenset({"utc", "gmt", self.tzname[0].lower()})333 if self.daylight:334 has_saving = frozenset({self.tzname[1].lower()})335 else:336 has_saving = frozenset()337 self.timezone = (no_saving, has_saving)338 339 340class TimeRE(dict):341 """Handle conversion from format directives to regexes."""342 343 def __init__(self, locale_time=None):344 """Create keys/values.345 346 Order of execution is important for dependency reasons.347 348 """349 if locale_time:350 self.locale_time = locale_time351 else:352 self.locale_time = LocaleTime()353 base = super()354 mapping = {355 # The " [1-9]" part of the regex is to make %c from ANSI C work356 'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])",357 'f': r"(?P<f>[0-9]{1,6})",358 'H': r"(?P<H>2[0-3]|[0-1]\d|\d| \d)",359 'k': r"(?P<H>2[0-3]|[0-1]\d|\d| \d)",360 'I': r"(?P<I>1[0-2]|0[1-9]|[1-9]| [1-9])",361 'l': r"(?P<I>1[0-2]|0[1-9]|[1-9]| [1-9])",362 'G': r"(?P<G>\d\d\d\d)",363 'j': r"(?P<j>36[0-6]|3[0-5]\d|[1-2]\d\d|0[1-9]\d|00[1-9]|[1-9]\d|0[1-9]|[1-9])",364 'm': r"(?P<m>1[0-2]|0[1-9]|[1-9])",365 'M': r"(?P<M>[0-5]\d|\d)",366 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)",367 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)",368 'w': r"(?P<w>[0-6])",369 'u': r"(?P<u>[1-7])",370 'V': r"(?P<V>5[0-3]|0[1-9]|[1-4]\d|\d)",371 # W is set below by using 'U'372 'y': r"(?P<y>\d\d)",373 'Y': r"(?P<Y>\d\d\d\d)",374 'z': r"(?P<z>[+-]\d\d:?[0-5]\d(:?[0-5]\d(\.\d{1,6})?)?|(?-i:Z))",375 'A': self.__seqToRE(self.locale_time.f_weekday, 'A'),376 'a': self.__seqToRE(self.locale_time.a_weekday, 'a'),377 'B': self.__seqToRE(_fixmonths(self.locale_time.f_month[1:]), 'B'),378 'b': self.__seqToRE(_fixmonths(self.locale_time.a_month[1:]), 'b'),379 'p': self.__seqToRE(self.locale_time.am_pm, 'p'),380 'Z': self.__seqToRE((tz for tz_names in self.locale_time.timezone381 for tz in tz_names),382 'Z'),383 '%': '%'}384 if self.locale_time.LC_alt_digits is None:385 for d in 'dmyCHIMS':386 mapping['O' + d] = r'(?P<%s>\d\d|\d| \d)' % d387 mapping['Ow'] = r'(?P<w>\d)'388 else:389 mapping.update({390 'Od': self.__seqToRE(self.locale_time.LC_alt_digits[1:32], 'd',391 '3[0-1]|[1-2][0-9]|0[1-9]|[1-9]'),392 'Om': self.__seqToRE(self.locale_time.LC_alt_digits[1:13], 'm',393 '1[0-2]|0[1-9]|[1-9]'),394 'Ow': self.__seqToRE(self.locale_time.LC_alt_digits[:7], 'w',395 '[0-6]'),396 'Oy': self.__seqToRE(self.locale_time.LC_alt_digits, 'y',397 '[0-9][0-9]'),398 'OC': self.__seqToRE(self.locale_time.LC_alt_digits, 'C',399 '[0-9][0-9]'),400 'OH': self.__seqToRE(self.locale_time.LC_alt_digits[:24], 'H',401 '2[0-3]|[0-1][0-9]|[0-9]'),402 'OI': self.__seqToRE(self.locale_time.LC_alt_digits[1:13], 'I',403 '1[0-2]|0[1-9]|[1-9]'),404 'OM': self.__seqToRE(self.locale_time.LC_alt_digits[:60], 'M',405 '[0-5][0-9]|[0-9]'),406 'OS': self.__seqToRE(self.locale_time.LC_alt_digits[:62], 'S',407 '6[0-1]|[0-5][0-9]|[0-9]'),408 })409 mapping.update({410 'e': mapping['d'],411 'Oe': mapping['Od'],412 'P': mapping['p'],413 'Op': mapping['p'],414 'W': mapping['U'].replace('U', 'W'),415 })416 mapping['W'] = mapping['U'].replace('U', 'W')417 418 base.__init__(mapping)419 base.__setitem__('T', self.pattern('%H:%M:%S'))420 base.__setitem__('R', self.pattern('%H:%M'))421 base.__setitem__('r', self.pattern(self.locale_time.LC_time_ampm))422 base.__setitem__('X', self.pattern(self.locale_time.LC_time))423 base.__setitem__('x', self.pattern(self.locale_time.LC_date))424 base.__setitem__('c', self.pattern(self.locale_time.LC_date_time))425 426 def __seqToRE(self, to_convert, directive, altregex=None):427 """Convert a list to a regex string for matching a directive.428 429 Want possible matching values to be from longest to shortest. This430 prevents the possibility of a match occurring for a value that also431 a substring of a larger value that should have matched (e.g., 'abc'432 matching when 'abcdef' should have been the match).433 434 """435 to_convert = sorted(to_convert, key=len, reverse=True)436 for value in to_convert:437 if value != '':438 break439 else:440 return ''441 regex = '|'.join(re_escape(stuff) for stuff in to_convert)442 if altregex is not None:443 regex += '|' + altregex444 return '(?P<%s>%s)' % (directive, regex)445 446 def pattern(self, format):447 """Return regex pattern for the format string.448 449 Need to make sure that any characters that might be interpreted as450 regex syntax are escaped.451 452 """453 # The sub() call escapes all characters that might be misconstrued454 # as regex syntax. Cannot use re.escape since we have to deal with455 # format directives (%m, etc.).456 format = re_sub(r"([\\.^$*+?\(\){}\[\]|])", r"\\\1", format)457 format = re_sub(r'\s+', r'\\s+', format)458 format = re_sub(r"'", "['\u02bc]", format) # needed for br_FR459 year_in_format = False460 day_of_month_in_format = False461 def repl(m):462 format_char = m[1]463 match format_char:464 case 'Y' | 'y' | 'G':465 nonlocal year_in_format466 year_in_format = True467 case 'd':468 nonlocal day_of_month_in_format469 day_of_month_in_format = True470 return self[format_char]471 format = re_sub(r'%[-_0^#]*[0-9]*([OE]?\\?.?)', repl, format)472 if day_of_month_in_format and not year_in_format:473 import warnings474 warnings.warn("""\475Parsing dates involving a day of month without a year specified is ambiguous476and fails to parse leap day. The default behavior will change in Python 3.15477to either always raise an exception or to use a different default year (TBD).478To avoid trouble, add a specific year to the input & format.479See https://github.com/python/cpython/issues/70647.""",480 DeprecationWarning,481 skip_file_prefixes=(os.path.dirname(__file__),))482 return format483 484 def compile(self, format):485 """Return a compiled re object for the format string."""486 return re_compile(self.pattern(format), IGNORECASE)487 488_cache_lock = _thread_allocate_lock()489# DO NOT modify _TimeRE_cache or _regex_cache without acquiring the cache lock490# first!491_TimeRE_cache = TimeRE()492_CACHE_MAX_SIZE = 5 # Max number of regexes stored in _regex_cache493_regex_cache = {}494 495def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon):496 """Calculate the Julian day based on the year, week of the year, and day of497 the week, with week_start_day representing whether the week of the year498 assumes the week starts on Sunday or Monday (6 or 0)."""499 first_weekday = datetime_date(year, 1, 1).weekday()500 # If we are dealing with the %U directive (week starts on Sunday), it's501 # easier to just shift the view to Sunday being the first day of the502 # week.503 if not week_starts_Mon:504 first_weekday = (first_weekday + 1) % 7505 day_of_week = (day_of_week + 1) % 7506 # Need to watch out for a week 0 (when the first day of the year is not507 # the same as that specified by %U or %W).508 week_0_length = (7 - first_weekday) % 7509 if week_of_year == 0:510 return 1 + day_of_week - first_weekday511 else:512 days_to_week = week_0_length + (7 * (week_of_year - 1))513 return 1 + days_to_week + day_of_week514 515 516def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):517 """Return a 2-tuple consisting of a time struct and an int containing518 the number of microseconds based on the input string and the519 format string."""520 521 for index, arg in enumerate([data_string, format]):522 if not isinstance(arg, str):523 msg = "strptime() argument {} must be str, not {}"524 raise TypeError(msg.format(index, type(arg)))525 526 global _TimeRE_cache, _regex_cache527 with _cache_lock:528 locale_time = _TimeRE_cache.locale_time529 if (_getlang() != locale_time.lang or530 time.tzname != locale_time.tzname or531 time.daylight != locale_time.daylight):532 _TimeRE_cache = TimeRE()533 _regex_cache.clear()534 locale_time = _TimeRE_cache.locale_time535 if len(_regex_cache) > _CACHE_MAX_SIZE:536 _regex_cache.clear()537 format_regex = _regex_cache.get(format)538 if not format_regex:539 try:540 format_regex = _TimeRE_cache.compile(format)541 # KeyError raised when a bad format is found; can be specified as542 # \\, in which case it was a stray % but with a space after it543 except KeyError as err:544 bad_directive = err.args[0]545 del err546 bad_directive = bad_directive.replace('\\s', '')547 if not bad_directive:548 raise ValueError("stray %% in format '%s'" % format) from None549 bad_directive = bad_directive.replace('\\', '', 1)550 raise ValueError("'%s' is a bad directive in format '%s'" %551 (bad_directive, format)) from None552 _regex_cache[format] = format_regex553 found = format_regex.match(data_string)554 if not found:555 raise ValueError("time data %r does not match format %r" %556 (data_string, format))557 if len(data_string) != found.end():558 raise ValueError("unconverted data remains: %s" %559 data_string[found.end():])560 561 iso_year = year = None562 month = day = 1563 hour = minute = second = fraction = 0564 tz = -1565 gmtoff = None566 gmtoff_fraction = 0567 iso_week = week_of_year = None568 week_of_year_start = None569 # weekday and julian defaulted to None so as to signal need to calculate570 # values571 weekday = julian = None572 found_dict = found.groupdict()573 if locale_time.LC_alt_digits:574 def parse_int(s):575 try:576 return locale_time.LC_alt_digits.index(s)577 except ValueError:578 return int(s)579 else:580 parse_int = int581 582 for group_key in found_dict.keys():583 # Directives not explicitly handled below:584 # c, x, X585 # handled by making out of other directives586 # U, W587 # worthless without day of the week588 if group_key == 'y':589 year = parse_int(found_dict['y'])590 if 'C' in found_dict:591 century = parse_int(found_dict['C'])592 year += century * 100593 else:594 # Open Group specification for strptime() states that a %y595 #value in the range of [00, 68] is in the century 2000, while596 #[69,99] is in the century 1900597 if year <= 68:598 year += 2000599 else:600 year += 1900601 elif group_key == 'Y':602 year = int(found_dict['Y'])603 elif group_key == 'G':604 iso_year = int(found_dict['G'])605 elif group_key == 'm':606 month = parse_int(found_dict['m'])607 elif group_key == 'B':608 month = locale_time.f_month.index(found_dict['B'].lower())609 elif group_key == 'b':610 month = locale_time.a_month.index(found_dict['b'].lower())611 elif group_key == 'd':612 day = parse_int(found_dict['d'])613 elif group_key == 'H':614 hour = parse_int(found_dict['H'])615 elif group_key == 'I':616 hour = parse_int(found_dict['I'])617 ampm = found_dict.get('p', '').lower()618 # If there was no AM/PM indicator, we'll treat this like AM619 if ampm in ('', locale_time.am_pm[0]):620 # We're in AM so the hour is correct unless we're621 # looking at 12 midnight.622 # 12 midnight == 12 AM == hour 0623 if hour == 12:624 hour = 0625 elif ampm == locale_time.am_pm[1]:626 # We're in PM so we need to add 12 to the hour unless627 # we're looking at 12 noon.628 # 12 noon == 12 PM == hour 12629 if hour != 12:630 hour += 12631 elif group_key == 'M':632 minute = parse_int(found_dict['M'])633 elif group_key == 'S':634 second = parse_int(found_dict['S'])635 elif group_key == 'f':636 s = found_dict['f']637 # Pad to always return microseconds.638 s += "0" * (6 - len(s))639 fraction = int(s)640 elif group_key == 'A':641 weekday = locale_time.f_weekday.index(found_dict['A'].lower())642 elif group_key == 'a':643 weekday = locale_time.a_weekday.index(found_dict['a'].lower())644 elif group_key == 'w':645 weekday = int(found_dict['w'])646 if weekday == 0:647 weekday = 6648 else:649 weekday -= 1650 elif group_key == 'u':651 weekday = int(found_dict['u'])652 weekday -= 1653 elif group_key == 'j':654 julian = int(found_dict['j'])655 elif group_key in ('U', 'W'):656 week_of_year = int(found_dict[group_key])657 if group_key == 'U':658 # U starts week on Sunday.659 week_of_year_start = 6660 else:661 # W starts week on Monday.662 week_of_year_start = 0663 elif group_key == 'V':664 iso_week = int(found_dict['V'])665 elif group_key == 'z':666 z = found_dict['z']667 if z == 'Z':668 gmtoff = 0669 else:670 if z[3] == ':':671 z = z[:3] + z[4:]672 if len(z) > 5:673 if z[5] != ':':674 msg = f"Inconsistent use of : in {found_dict['z']}"675 raise ValueError(msg)676 z = z[:5] + z[6:]677 hours = int(z[1:3])678 minutes = int(z[3:5])679 seconds = int(z[5:7] or 0)680 gmtoff = (hours * 60 * 60) + (minutes * 60) + seconds681 gmtoff_remainder = z[8:]682 # Pad to always return microseconds.683 gmtoff_remainder_padding = "0" * (6 - len(gmtoff_remainder))684 gmtoff_fraction = int(gmtoff_remainder + gmtoff_remainder_padding)685 if z.startswith("-"):686 gmtoff = -gmtoff687 gmtoff_fraction = -gmtoff_fraction688 elif group_key == 'Z':689 # Since -1 is default value only need to worry about setting tz if690 # it can be something other than -1.691 found_zone = found_dict['Z'].lower()692 for value, tz_values in enumerate(locale_time.timezone):693 if found_zone in tz_values:694 # Deal with bad locale setup where timezone names are the695 # same and yet time.daylight is true; too ambiguous to696 # be able to tell what timezone has daylight savings697 if (time.tzname[0] == time.tzname[1] and698 time.daylight and found_zone not in ("utc", "gmt")):699 break700 else:701 tz = value702 break703 704 # Deal with the cases where ambiguities arise705 # don't assume default values for ISO week/year706 if iso_year is not None:707 if julian is not None:708 raise ValueError("Day of the year directive '%j' is not "709 "compatible with ISO year directive '%G'. "710 "Use '%Y' instead.")711 elif iso_week is None or weekday is None:712 raise ValueError("ISO year directive '%G' must be used with "713 "the ISO week directive '%V' and a weekday "714 "directive ('%A', '%a', '%w', or '%u').")715 elif iso_week is not None:716 if year is None or weekday is None:717 raise ValueError("ISO week directive '%V' must be used with "718 "the ISO year directive '%G' and a weekday "719 "directive ('%A', '%a', '%w', or '%u').")720 else:721 raise ValueError("ISO week directive '%V' is incompatible with "722 "the year directive '%Y'. Use the ISO year '%G' "723 "instead.")724 725 leap_year_fix = False726 if year is None:727 if month == 2 and day == 29:728 year = 1904 # 1904 is first leap year of 20th century729 leap_year_fix = True730 else:731 year = 1900732 733 # If we know the week of the year and what day of that week, we can figure734 # out the Julian day of the year.735 if julian is None and weekday is not None:736 if week_of_year is not None:737 week_starts_Mon = True if week_of_year_start == 0 else False738 julian = _calc_julian_from_U_or_W(year, week_of_year, weekday,739 week_starts_Mon)740 elif iso_year is not None and iso_week is not None:741 datetime_result = datetime_date.fromisocalendar(iso_year, iso_week, weekday + 1)742 year = datetime_result.year743 month = datetime_result.month744 day = datetime_result.day745 if julian is not None and julian <= 0:746 year -= 1747 yday = 366 if calendar.isleap(year) else 365748 julian += yday749 750 if julian is None:751 # Cannot pre-calculate datetime_date() since can change in Julian752 # calculation and thus could have different value for the day of753 # the week calculation.754 # Need to add 1 to result since first day of the year is 1, not 0.755 julian = datetime_date(year, month, day).toordinal() - \756 datetime_date(year, 1, 1).toordinal() + 1757 else: # Assume that if they bothered to include Julian day (or if it was758 # calculated above with year/week/weekday) it will be accurate.759 datetime_result = datetime_date.fromordinal(760 (julian - 1) +761 datetime_date(year, 1, 1).toordinal())762 year = datetime_result.year763 month = datetime_result.month764 day = datetime_result.day765 if weekday is None:766 weekday = datetime_date(year, month, day).weekday()767 # Add timezone info768 tzname = found_dict.get("Z")769 770 if leap_year_fix:771 # the caller didn't supply a year but asked for Feb 29th. We couldn't772 # use the default of 1900 for computations. We set it back to ensure773 # that February 29th is smaller than March 1st.774 year = 1900775 776 return (year, month, day,777 hour, minute, second,778 weekday, julian, tz, tzname, gmtoff), fraction, gmtoff_fraction779 780def _strptime_time(data_string, format="%a %b %d %H:%M:%S %Y"):781 """Return a time struct based on the input string and the782 format string."""783 tt = _strptime(data_string, format)[0]784 return time.struct_time(tt[:time._STRUCT_TM_ITEMS])785 786def _strptime_datetime_date(cls, data_string, format="%a %b %d %Y"):787 """Return a date instance based on the input string and the788 format string."""789 tt, _, _ = _strptime(data_string, format)790 args = tt[:3]791 return cls(*args)792 793def _parse_tz(tzname, gmtoff, gmtoff_fraction):794 tzdelta = datetime_timedelta(seconds=gmtoff, microseconds=gmtoff_fraction)795 if tzname:796 return datetime_timezone(tzdelta, tzname)797 else:798 return datetime_timezone(tzdelta)799 800def _strptime_datetime_time(cls, data_string, format="%H:%M:%S"):801 """Return a time instance based on the input string and the802 format string."""803 tt, fraction, gmtoff_fraction = _strptime(data_string, format)804 tzname, gmtoff = tt[-2:]805 args = tt[3:6] + (fraction,)806 if gmtoff is None:807 return cls(*args)808 else:809 tz = _parse_tz(tzname, gmtoff, gmtoff_fraction)810 return cls(*args, tz)811 812def _strptime_datetime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):813 """Return a datetime instance based on the input string and the814 format string."""815 tt, fraction, gmtoff_fraction = _strptime(data_string, format)816 tzname, gmtoff = tt[-2:]817 args = tt[:6] + (fraction,)818 if gmtoff is None:819 return cls(*args)820 else:821 tz = _parse_tz(tzname, gmtoff, gmtoff_fraction)822 return cls(*args, tz)823 