_strptime.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. """Strptime-related classes and functions.
  2. CLASSES:
  3. LocaleTime -- Discovers and stores locale-specific time information
  4. TimeRE -- Creates regexes for pattern matching a string of text containing
  5. time information
  6. FUNCTIONS:
  7. _getlang -- Figure out what language is being used for the locale
  8. strptime -- Calculates the time struct represented by the passed-in string
  9. """
  10. import time
  11. import locale
  12. import calendar
  13. from re import compile as re_compile
  14. from re import IGNORECASE
  15. from re import escape as re_escape
  16. from datetime import (date as datetime_date,
  17. timedelta as datetime_timedelta,
  18. timezone as datetime_timezone)
  19. from _thread import allocate_lock as _thread_allocate_lock
  20. __all__ = []
  21. def _getlang():
  22. # Figure out what the current language is set to.
  23. return locale.getlocale(locale.LC_TIME)
  24. class LocaleTime(object):
  25. """Stores and handles locale-specific information related to time.
  26. ATTRIBUTES:
  27. f_weekday -- full weekday names (7-item list)
  28. a_weekday -- abbreviated weekday names (7-item list)
  29. f_month -- full month names (13-item list; dummy value in [0], which
  30. is added by code)
  31. a_month -- abbreviated month names (13-item list, dummy value in
  32. [0], which is added by code)
  33. am_pm -- AM/PM representation (2-item list)
  34. LC_date_time -- format string for date/time representation (string)
  35. LC_date -- format string for date representation (string)
  36. LC_time -- format string for time representation (string)
  37. timezone -- daylight- and non-daylight-savings timezone representation
  38. (2-item list of sets)
  39. lang -- Language used by instance (2-item tuple)
  40. """
  41. def __init__(self):
  42. """Set all attributes.
  43. Order of methods called matters for dependency reasons.
  44. The locale language is set at the offset and then checked again before
  45. exiting. This is to make sure that the attributes were not set with a
  46. mix of information from more than one locale. This would most likely
  47. happen when using threads where one thread calls a locale-dependent
  48. function while another thread changes the locale while the function in
  49. the other thread is still running. Proper coding would call for
  50. locks to prevent changing the locale while locale-dependent code is
  51. running. The check here is done in case someone does not think about
  52. doing this.
  53. Only other possible issue is if someone changed the timezone and did
  54. not call tz.tzset . That is an issue for the programmer, though,
  55. since changing the timezone is worthless without that call.
  56. """
  57. self.lang = _getlang()
  58. self.__calc_weekday()
  59. self.__calc_month()
  60. self.__calc_am_pm()
  61. self.__calc_timezone()
  62. self.__calc_date_time()
  63. if _getlang() != self.lang:
  64. raise ValueError("locale changed during initialization")
  65. if time.tzname != self.tzname or time.daylight != self.daylight:
  66. raise ValueError("timezone changed during initialization")
  67. def __calc_weekday(self):
  68. # Set self.a_weekday and self.f_weekday using the calendar
  69. # module.
  70. a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
  71. f_weekday = [calendar.day_name[i].lower() for i in range(7)]
  72. self.a_weekday = a_weekday
  73. self.f_weekday = f_weekday
  74. def __calc_month(self):
  75. # Set self.f_month and self.a_month using the calendar module.
  76. a_month = [calendar.month_abbr[i].lower() for i in range(13)]
  77. f_month = [calendar.month_name[i].lower() for i in range(13)]
  78. self.a_month = a_month
  79. self.f_month = f_month
  80. def __calc_am_pm(self):
  81. # Set self.am_pm by using time.strftime().
  82. # The magic date (1999,3,17,hour,44,55,2,76,0) is not really that
  83. # magical; just happened to have used it everywhere else where a
  84. # static date was needed.
  85. am_pm = []
  86. for hour in (1, 22):
  87. time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0))
  88. am_pm.append(time.strftime("%p", time_tuple).lower())
  89. self.am_pm = am_pm
  90. def __calc_date_time(self):
  91. # Set self.date_time, self.date, & self.time by using
  92. # time.strftime().
  93. # Use (1999,3,17,22,44,55,2,76,0) for magic date because the amount of
  94. # overloaded numbers is minimized. The order in which searches for
  95. # values within the format string is very important; it eliminates
  96. # possible ambiguity for what something represents.
  97. time_tuple = time.struct_time((1999,3,17,22,44,55,2,76,0))
  98. date_time = [None, None, None]
  99. date_time[0] = time.strftime("%c", time_tuple).lower()
  100. date_time[1] = time.strftime("%x", time_tuple).lower()
  101. date_time[2] = time.strftime("%X", time_tuple).lower()
  102. replacement_pairs = [('%', '%%'), (self.f_weekday[2], '%A'),
  103. (self.f_month[3], '%B'), (self.a_weekday[2], '%a'),
  104. (self.a_month[3], '%b'), (self.am_pm[1], '%p'),
  105. ('1999', '%Y'), ('99', '%y'), ('22', '%H'),
  106. ('44', '%M'), ('55', '%S'), ('76', '%j'),
  107. ('17', '%d'), ('03', '%m'), ('3', '%m'),
  108. # '3' needed for when no leading zero.
  109. ('2', '%w'), ('10', '%I')]
  110. replacement_pairs.extend([(tz, "%Z") for tz_values in self.timezone
  111. for tz in tz_values])
  112. for offset,directive in ((0,'%c'), (1,'%x'), (2,'%X')):
  113. current_format = date_time[offset]
  114. for old, new in replacement_pairs:
  115. # Must deal with possible lack of locale info
  116. # manifesting itself as the empty string (e.g., Swedish's
  117. # lack of AM/PM info) or a platform returning a tuple of empty
  118. # strings (e.g., MacOS 9 having timezone as ('','')).
  119. if old:
  120. current_format = current_format.replace(old, new)
  121. # If %W is used, then Sunday, 2005-01-03 will fall on week 0 since
  122. # 2005-01-03 occurs before the first Monday of the year. Otherwise
  123. # %U is used.
  124. time_tuple = time.struct_time((1999,1,3,1,1,1,6,3,0))
  125. if '00' in time.strftime(directive, time_tuple):
  126. U_W = '%W'
  127. else:
  128. U_W = '%U'
  129. date_time[offset] = current_format.replace('11', U_W)
  130. self.LC_date_time = date_time[0]
  131. self.LC_date = date_time[1]
  132. self.LC_time = date_time[2]
  133. def __calc_timezone(self):
  134. # Set self.timezone by using time.tzname.
  135. # Do not worry about possibility of time.tzname[0] == time.tzname[1]
  136. # and time.daylight; handle that in strptime.
  137. try:
  138. time.tzset()
  139. except AttributeError:
  140. pass
  141. self.tzname = time.tzname
  142. self.daylight = time.daylight
  143. no_saving = frozenset({"utc", "gmt", self.tzname[0].lower()})
  144. if self.daylight:
  145. has_saving = frozenset({self.tzname[1].lower()})
  146. else:
  147. has_saving = frozenset()
  148. self.timezone = (no_saving, has_saving)
  149. class TimeRE(dict):
  150. """Handle conversion from format directives to regexes."""
  151. def __init__(self, locale_time=None):
  152. """Create keys/values.
  153. Order of execution is important for dependency reasons.
  154. """
  155. if locale_time:
  156. self.locale_time = locale_time
  157. else:
  158. self.locale_time = LocaleTime()
  159. base = super()
  160. base.__init__({
  161. # The " [1-9]" part of the regex is to make %c from ANSI C work
  162. 'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])",
  163. 'f': r"(?P<f>[0-9]{1,6})",
  164. 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)",
  165. 'I': r"(?P<I>1[0-2]|0[1-9]|[1-9])",
  166. 'G': r"(?P<G>\d\d\d\d)",
  167. '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])",
  168. 'm': r"(?P<m>1[0-2]|0[1-9]|[1-9])",
  169. 'M': r"(?P<M>[0-5]\d|\d)",
  170. 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)",
  171. 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)",
  172. 'w': r"(?P<w>[0-6])",
  173. 'u': r"(?P<u>[1-7])",
  174. 'V': r"(?P<V>5[0-3]|0[1-9]|[1-4]\d|\d)",
  175. # W is set below by using 'U'
  176. 'y': r"(?P<y>\d\d)",
  177. #XXX: Does 'Y' need to worry about having less or more than
  178. # 4 digits?
  179. 'Y': r"(?P<Y>\d\d\d\d)",
  180. 'z': r"(?P<z>[+-]\d\d:?[0-5]\d(:?[0-5]\d(\.\d{1,6})?)?|(?-i:Z))",
  181. 'A': self.__seqToRE(self.locale_time.f_weekday, 'A'),
  182. 'a': self.__seqToRE(self.locale_time.a_weekday, 'a'),
  183. 'B': self.__seqToRE(self.locale_time.f_month[1:], 'B'),
  184. 'b': self.__seqToRE(self.locale_time.a_month[1:], 'b'),
  185. 'p': self.__seqToRE(self.locale_time.am_pm, 'p'),
  186. 'Z': self.__seqToRE((tz for tz_names in self.locale_time.timezone
  187. for tz in tz_names),
  188. 'Z'),
  189. '%': '%'})
  190. base.__setitem__('W', base.__getitem__('U').replace('U', 'W'))
  191. base.__setitem__('c', self.pattern(self.locale_time.LC_date_time))
  192. base.__setitem__('x', self.pattern(self.locale_time.LC_date))
  193. base.__setitem__('X', self.pattern(self.locale_time.LC_time))
  194. def __seqToRE(self, to_convert, directive):
  195. """Convert a list to a regex string for matching a directive.
  196. Want possible matching values to be from longest to shortest. This
  197. prevents the possibility of a match occurring for a value that also
  198. a substring of a larger value that should have matched (e.g., 'abc'
  199. matching when 'abcdef' should have been the match).
  200. """
  201. to_convert = sorted(to_convert, key=len, reverse=True)
  202. for value in to_convert:
  203. if value != '':
  204. break
  205. else:
  206. return ''
  207. regex = '|'.join(re_escape(stuff) for stuff in to_convert)
  208. regex = '(?P<%s>%s' % (directive, regex)
  209. return '%s)' % regex
  210. def pattern(self, format):
  211. """Return regex pattern for the format string.
  212. Need to make sure that any characters that might be interpreted as
  213. regex syntax are escaped.
  214. """
  215. processed_format = ''
  216. # The sub() call escapes all characters that might be misconstrued
  217. # as regex syntax. Cannot use re.escape since we have to deal with
  218. # format directives (%m, etc.).
  219. regex_chars = re_compile(r"([\\.^$*+?\(\){}\[\]|])")
  220. format = regex_chars.sub(r"\\\1", format)
  221. whitespace_replacement = re_compile(r'\s+')
  222. format = whitespace_replacement.sub(r'\\s+', format)
  223. while '%' in format:
  224. directive_index = format.index('%')+1
  225. processed_format = "%s%s%s" % (processed_format,
  226. format[:directive_index-1],
  227. self[format[directive_index]])
  228. format = format[directive_index+1:]
  229. return "%s%s" % (processed_format, format)
  230. def compile(self, format):
  231. """Return a compiled re object for the format string."""
  232. return re_compile(self.pattern(format), IGNORECASE)
  233. _cache_lock = _thread_allocate_lock()
  234. # DO NOT modify _TimeRE_cache or _regex_cache without acquiring the cache lock
  235. # first!
  236. _TimeRE_cache = TimeRE()
  237. _CACHE_MAX_SIZE = 5 # Max number of regexes stored in _regex_cache
  238. _regex_cache = {}
  239. def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon):
  240. """Calculate the Julian day based on the year, week of the year, and day of
  241. the week, with week_start_day representing whether the week of the year
  242. assumes the week starts on Sunday or Monday (6 or 0)."""
  243. first_weekday = datetime_date(year, 1, 1).weekday()
  244. # If we are dealing with the %U directive (week starts on Sunday), it's
  245. # easier to just shift the view to Sunday being the first day of the
  246. # week.
  247. if not week_starts_Mon:
  248. first_weekday = (first_weekday + 1) % 7
  249. day_of_week = (day_of_week + 1) % 7
  250. # Need to watch out for a week 0 (when the first day of the year is not
  251. # the same as that specified by %U or %W).
  252. week_0_length = (7 - first_weekday) % 7
  253. if week_of_year == 0:
  254. return 1 + day_of_week - first_weekday
  255. else:
  256. days_to_week = week_0_length + (7 * (week_of_year - 1))
  257. return 1 + days_to_week + day_of_week
  258. def _calc_julian_from_V(iso_year, iso_week, iso_weekday):
  259. """Calculate the Julian day based on the ISO 8601 year, week, and weekday.
  260. ISO weeks start on Mondays, with week 01 being the week containing 4 Jan.
  261. ISO week days range from 1 (Monday) to 7 (Sunday).
  262. """
  263. correction = datetime_date(iso_year, 1, 4).isoweekday() + 3
  264. ordinal = (iso_week * 7) + iso_weekday - correction
  265. # ordinal may be negative or 0 now, which means the date is in the previous
  266. # calendar year
  267. if ordinal < 1:
  268. ordinal += datetime_date(iso_year, 1, 1).toordinal()
  269. iso_year -= 1
  270. ordinal -= datetime_date(iso_year, 1, 1).toordinal()
  271. return iso_year, ordinal
  272. def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
  273. """Return a 2-tuple consisting of a time struct and an int containing
  274. the number of microseconds based on the input string and the
  275. format string."""
  276. for index, arg in enumerate([data_string, format]):
  277. if not isinstance(arg, str):
  278. msg = "strptime() argument {} must be str, not {}"
  279. raise TypeError(msg.format(index, type(arg)))
  280. global _TimeRE_cache, _regex_cache
  281. with _cache_lock:
  282. locale_time = _TimeRE_cache.locale_time
  283. if (_getlang() != locale_time.lang or
  284. time.tzname != locale_time.tzname or
  285. time.daylight != locale_time.daylight):
  286. _TimeRE_cache = TimeRE()
  287. _regex_cache.clear()
  288. locale_time = _TimeRE_cache.locale_time
  289. if len(_regex_cache) > _CACHE_MAX_SIZE:
  290. _regex_cache.clear()
  291. format_regex = _regex_cache.get(format)
  292. if not format_regex:
  293. try:
  294. format_regex = _TimeRE_cache.compile(format)
  295. # KeyError raised when a bad format is found; can be specified as
  296. # \\, in which case it was a stray % but with a space after it
  297. except KeyError as err:
  298. bad_directive = err.args[0]
  299. if bad_directive == "\\":
  300. bad_directive = "%"
  301. del err
  302. raise ValueError("'%s' is a bad directive in format '%s'" %
  303. (bad_directive, format)) from None
  304. # IndexError only occurs when the format string is "%"
  305. except IndexError:
  306. raise ValueError("stray %% in format '%s'" % format) from None
  307. _regex_cache[format] = format_regex
  308. found = format_regex.match(data_string)
  309. if not found:
  310. raise ValueError("time data %r does not match format %r" %
  311. (data_string, format))
  312. if len(data_string) != found.end():
  313. raise ValueError("unconverted data remains: %s" %
  314. data_string[found.end():])
  315. iso_year = year = None
  316. month = day = 1
  317. hour = minute = second = fraction = 0
  318. tz = -1
  319. gmtoff = None
  320. gmtoff_fraction = 0
  321. # Default to -1 to signify that values not known; not critical to have,
  322. # though
  323. iso_week = week_of_year = None
  324. week_of_year_start = None
  325. # weekday and julian defaulted to None so as to signal need to calculate
  326. # values
  327. weekday = julian = None
  328. found_dict = found.groupdict()
  329. for group_key in found_dict.keys():
  330. # Directives not explicitly handled below:
  331. # c, x, X
  332. # handled by making out of other directives
  333. # U, W
  334. # worthless without day of the week
  335. if group_key == 'y':
  336. year = int(found_dict['y'])
  337. # Open Group specification for strptime() states that a %y
  338. #value in the range of [00, 68] is in the century 2000, while
  339. #[69,99] is in the century 1900
  340. if year <= 68:
  341. year += 2000
  342. else:
  343. year += 1900
  344. elif group_key == 'Y':
  345. year = int(found_dict['Y'])
  346. elif group_key == 'G':
  347. iso_year = int(found_dict['G'])
  348. elif group_key == 'm':
  349. month = int(found_dict['m'])
  350. elif group_key == 'B':
  351. month = locale_time.f_month.index(found_dict['B'].lower())
  352. elif group_key == 'b':
  353. month = locale_time.a_month.index(found_dict['b'].lower())
  354. elif group_key == 'd':
  355. day = int(found_dict['d'])
  356. elif group_key == 'H':
  357. hour = int(found_dict['H'])
  358. elif group_key == 'I':
  359. hour = int(found_dict['I'])
  360. ampm = found_dict.get('p', '').lower()
  361. # If there was no AM/PM indicator, we'll treat this like AM
  362. if ampm in ('', locale_time.am_pm[0]):
  363. # We're in AM so the hour is correct unless we're
  364. # looking at 12 midnight.
  365. # 12 midnight == 12 AM == hour 0
  366. if hour == 12:
  367. hour = 0
  368. elif ampm == locale_time.am_pm[1]:
  369. # We're in PM so we need to add 12 to the hour unless
  370. # we're looking at 12 noon.
  371. # 12 noon == 12 PM == hour 12
  372. if hour != 12:
  373. hour += 12
  374. elif group_key == 'M':
  375. minute = int(found_dict['M'])
  376. elif group_key == 'S':
  377. second = int(found_dict['S'])
  378. elif group_key == 'f':
  379. s = found_dict['f']
  380. # Pad to always return microseconds.
  381. s += "0" * (6 - len(s))
  382. fraction = int(s)
  383. elif group_key == 'A':
  384. weekday = locale_time.f_weekday.index(found_dict['A'].lower())
  385. elif group_key == 'a':
  386. weekday = locale_time.a_weekday.index(found_dict['a'].lower())
  387. elif group_key == 'w':
  388. weekday = int(found_dict['w'])
  389. if weekday == 0:
  390. weekday = 6
  391. else:
  392. weekday -= 1
  393. elif group_key == 'u':
  394. weekday = int(found_dict['u'])
  395. weekday -= 1
  396. elif group_key == 'j':
  397. julian = int(found_dict['j'])
  398. elif group_key in ('U', 'W'):
  399. week_of_year = int(found_dict[group_key])
  400. if group_key == 'U':
  401. # U starts week on Sunday.
  402. week_of_year_start = 6
  403. else:
  404. # W starts week on Monday.
  405. week_of_year_start = 0
  406. elif group_key == 'V':
  407. iso_week = int(found_dict['V'])
  408. elif group_key == 'z':
  409. z = found_dict['z']
  410. if z == 'Z':
  411. gmtoff = 0
  412. else:
  413. if z[3] == ':':
  414. z = z[:3] + z[4:]
  415. if len(z) > 5:
  416. if z[5] != ':':
  417. msg = f"Inconsistent use of : in {found_dict['z']}"
  418. raise ValueError(msg)
  419. z = z[:5] + z[6:]
  420. hours = int(z[1:3])
  421. minutes = int(z[3:5])
  422. seconds = int(z[5:7] or 0)
  423. gmtoff = (hours * 60 * 60) + (minutes * 60) + seconds
  424. gmtoff_remainder = z[8:]
  425. # Pad to always return microseconds.
  426. gmtoff_remainder_padding = "0" * (6 - len(gmtoff_remainder))
  427. gmtoff_fraction = int(gmtoff_remainder + gmtoff_remainder_padding)
  428. if z.startswith("-"):
  429. gmtoff = -gmtoff
  430. gmtoff_fraction = -gmtoff_fraction
  431. elif group_key == 'Z':
  432. # Since -1 is default value only need to worry about setting tz if
  433. # it can be something other than -1.
  434. found_zone = found_dict['Z'].lower()
  435. for value, tz_values in enumerate(locale_time.timezone):
  436. if found_zone in tz_values:
  437. # Deal with bad locale setup where timezone names are the
  438. # same and yet time.daylight is true; too ambiguous to
  439. # be able to tell what timezone has daylight savings
  440. if (time.tzname[0] == time.tzname[1] and
  441. time.daylight and found_zone not in ("utc", "gmt")):
  442. break
  443. else:
  444. tz = value
  445. break
  446. # Deal with the cases where ambiguities arize
  447. # don't assume default values for ISO week/year
  448. if year is None and iso_year is not None:
  449. if iso_week is None or weekday is None:
  450. raise ValueError("ISO year directive '%G' must be used with "
  451. "the ISO week directive '%V' and a weekday "
  452. "directive ('%A', '%a', '%w', or '%u').")
  453. if julian is not None:
  454. raise ValueError("Day of the year directive '%j' is not "
  455. "compatible with ISO year directive '%G'. "
  456. "Use '%Y' instead.")
  457. elif week_of_year is None and iso_week is not None:
  458. if weekday is None:
  459. raise ValueError("ISO week directive '%V' must be used with "
  460. "the ISO year directive '%G' and a weekday "
  461. "directive ('%A', '%a', '%w', or '%u').")
  462. else:
  463. raise ValueError("ISO week directive '%V' is incompatible with "
  464. "the year directive '%Y'. Use the ISO year '%G' "
  465. "instead.")
  466. leap_year_fix = False
  467. if year is None and month == 2 and day == 29:
  468. year = 1904 # 1904 is first leap year of 20th century
  469. leap_year_fix = True
  470. elif year is None:
  471. year = 1900
  472. # If we know the week of the year and what day of that week, we can figure
  473. # out the Julian day of the year.
  474. if julian is None and weekday is not None:
  475. if week_of_year is not None:
  476. week_starts_Mon = True if week_of_year_start == 0 else False
  477. julian = _calc_julian_from_U_or_W(year, week_of_year, weekday,
  478. week_starts_Mon)
  479. elif iso_year is not None and iso_week is not None:
  480. year, julian = _calc_julian_from_V(iso_year, iso_week, weekday + 1)
  481. if julian is not None and julian <= 0:
  482. year -= 1
  483. yday = 366 if calendar.isleap(year) else 365
  484. julian += yday
  485. if julian is None:
  486. # Cannot pre-calculate datetime_date() since can change in Julian
  487. # calculation and thus could have different value for the day of
  488. # the week calculation.
  489. # Need to add 1 to result since first day of the year is 1, not 0.
  490. julian = datetime_date(year, month, day).toordinal() - \
  491. datetime_date(year, 1, 1).toordinal() + 1
  492. else: # Assume that if they bothered to include Julian day (or if it was
  493. # calculated above with year/week/weekday) it will be accurate.
  494. datetime_result = datetime_date.fromordinal(
  495. (julian - 1) +
  496. datetime_date(year, 1, 1).toordinal())
  497. year = datetime_result.year
  498. month = datetime_result.month
  499. day = datetime_result.day
  500. if weekday is None:
  501. weekday = datetime_date(year, month, day).weekday()
  502. # Add timezone info
  503. tzname = found_dict.get("Z")
  504. if leap_year_fix:
  505. # the caller didn't supply a year but asked for Feb 29th. We couldn't
  506. # use the default of 1900 for computations. We set it back to ensure
  507. # that February 29th is smaller than March 1st.
  508. year = 1900
  509. return (year, month, day,
  510. hour, minute, second,
  511. weekday, julian, tz, tzname, gmtoff), fraction, gmtoff_fraction
  512. def _strptime_time(data_string, format="%a %b %d %H:%M:%S %Y"):
  513. """Return a time struct based on the input string and the
  514. format string."""
  515. tt = _strptime(data_string, format)[0]
  516. return time.struct_time(tt[:time._STRUCT_TM_ITEMS])
  517. def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):
  518. """Return a class cls instance based on the input string and the
  519. format string."""
  520. tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  521. tzname, gmtoff = tt[-2:]
  522. args = tt[:6] + (fraction,)
  523. if gmtoff is not None:
  524. tzdelta = datetime_timedelta(seconds=gmtoff, microseconds=gmtoff_fraction)
  525. if tzname:
  526. tz = datetime_timezone(tzdelta, tzname)
  527. else:
  528. tz = datetime_timezone(tzdelta)
  529. args += (tz,)
  530. return cls(*args)