_strptime.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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 _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
  259. """Return a 2-tuple consisting of a time struct and an int containing
  260. the number of microseconds based on the input string and the
  261. format string."""
  262. for index, arg in enumerate([data_string, format]):
  263. if not isinstance(arg, str):
  264. msg = "strptime() argument {} must be str, not {}"
  265. raise TypeError(msg.format(index, type(arg)))
  266. global _TimeRE_cache, _regex_cache
  267. with _cache_lock:
  268. locale_time = _TimeRE_cache.locale_time
  269. if (_getlang() != locale_time.lang or
  270. time.tzname != locale_time.tzname or
  271. time.daylight != locale_time.daylight):
  272. _TimeRE_cache = TimeRE()
  273. _regex_cache.clear()
  274. locale_time = _TimeRE_cache.locale_time
  275. if len(_regex_cache) > _CACHE_MAX_SIZE:
  276. _regex_cache.clear()
  277. format_regex = _regex_cache.get(format)
  278. if not format_regex:
  279. try:
  280. format_regex = _TimeRE_cache.compile(format)
  281. # KeyError raised when a bad format is found; can be specified as
  282. # \\, in which case it was a stray % but with a space after it
  283. except KeyError as err:
  284. bad_directive = err.args[0]
  285. if bad_directive == "\\":
  286. bad_directive = "%"
  287. del err
  288. raise ValueError("'%s' is a bad directive in format '%s'" %
  289. (bad_directive, format)) from None
  290. # IndexError only occurs when the format string is "%"
  291. except IndexError:
  292. raise ValueError("stray %% in format '%s'" % format) from None
  293. _regex_cache[format] = format_regex
  294. found = format_regex.match(data_string)
  295. if not found:
  296. raise ValueError("time data %r does not match format %r" %
  297. (data_string, format))
  298. if len(data_string) != found.end():
  299. raise ValueError("unconverted data remains: %s" %
  300. data_string[found.end():])
  301. iso_year = year = None
  302. month = day = 1
  303. hour = minute = second = fraction = 0
  304. tz = -1
  305. gmtoff = None
  306. gmtoff_fraction = 0
  307. # Default to -1 to signify that values not known; not critical to have,
  308. # though
  309. iso_week = week_of_year = None
  310. week_of_year_start = None
  311. # weekday and julian defaulted to None so as to signal need to calculate
  312. # values
  313. weekday = julian = None
  314. found_dict = found.groupdict()
  315. for group_key in found_dict.keys():
  316. # Directives not explicitly handled below:
  317. # c, x, X
  318. # handled by making out of other directives
  319. # U, W
  320. # worthless without day of the week
  321. if group_key == 'y':
  322. year = int(found_dict['y'])
  323. # Open Group specification for strptime() states that a %y
  324. #value in the range of [00, 68] is in the century 2000, while
  325. #[69,99] is in the century 1900
  326. if year <= 68:
  327. year += 2000
  328. else:
  329. year += 1900
  330. elif group_key == 'Y':
  331. year = int(found_dict['Y'])
  332. elif group_key == 'G':
  333. iso_year = int(found_dict['G'])
  334. elif group_key == 'm':
  335. month = int(found_dict['m'])
  336. elif group_key == 'B':
  337. month = locale_time.f_month.index(found_dict['B'].lower())
  338. elif group_key == 'b':
  339. month = locale_time.a_month.index(found_dict['b'].lower())
  340. elif group_key == 'd':
  341. day = int(found_dict['d'])
  342. elif group_key == 'H':
  343. hour = int(found_dict['H'])
  344. elif group_key == 'I':
  345. hour = int(found_dict['I'])
  346. ampm = found_dict.get('p', '').lower()
  347. # If there was no AM/PM indicator, we'll treat this like AM
  348. if ampm in ('', locale_time.am_pm[0]):
  349. # We're in AM so the hour is correct unless we're
  350. # looking at 12 midnight.
  351. # 12 midnight == 12 AM == hour 0
  352. if hour == 12:
  353. hour = 0
  354. elif ampm == locale_time.am_pm[1]:
  355. # We're in PM so we need to add 12 to the hour unless
  356. # we're looking at 12 noon.
  357. # 12 noon == 12 PM == hour 12
  358. if hour != 12:
  359. hour += 12
  360. elif group_key == 'M':
  361. minute = int(found_dict['M'])
  362. elif group_key == 'S':
  363. second = int(found_dict['S'])
  364. elif group_key == 'f':
  365. s = found_dict['f']
  366. # Pad to always return microseconds.
  367. s += "0" * (6 - len(s))
  368. fraction = int(s)
  369. elif group_key == 'A':
  370. weekday = locale_time.f_weekday.index(found_dict['A'].lower())
  371. elif group_key == 'a':
  372. weekday = locale_time.a_weekday.index(found_dict['a'].lower())
  373. elif group_key == 'w':
  374. weekday = int(found_dict['w'])
  375. if weekday == 0:
  376. weekday = 6
  377. else:
  378. weekday -= 1
  379. elif group_key == 'u':
  380. weekday = int(found_dict['u'])
  381. weekday -= 1
  382. elif group_key == 'j':
  383. julian = int(found_dict['j'])
  384. elif group_key in ('U', 'W'):
  385. week_of_year = int(found_dict[group_key])
  386. if group_key == 'U':
  387. # U starts week on Sunday.
  388. week_of_year_start = 6
  389. else:
  390. # W starts week on Monday.
  391. week_of_year_start = 0
  392. elif group_key == 'V':
  393. iso_week = int(found_dict['V'])
  394. elif group_key == 'z':
  395. z = found_dict['z']
  396. if z == 'Z':
  397. gmtoff = 0
  398. else:
  399. if z[3] == ':':
  400. z = z[:3] + z[4:]
  401. if len(z) > 5:
  402. if z[5] != ':':
  403. msg = f"Inconsistent use of : in {found_dict['z']}"
  404. raise ValueError(msg)
  405. z = z[:5] + z[6:]
  406. hours = int(z[1:3])
  407. minutes = int(z[3:5])
  408. seconds = int(z[5:7] or 0)
  409. gmtoff = (hours * 60 * 60) + (minutes * 60) + seconds
  410. gmtoff_remainder = z[8:]
  411. # Pad to always return microseconds.
  412. gmtoff_remainder_padding = "0" * (6 - len(gmtoff_remainder))
  413. gmtoff_fraction = int(gmtoff_remainder + gmtoff_remainder_padding)
  414. if z.startswith("-"):
  415. gmtoff = -gmtoff
  416. gmtoff_fraction = -gmtoff_fraction
  417. elif group_key == 'Z':
  418. # Since -1 is default value only need to worry about setting tz if
  419. # it can be something other than -1.
  420. found_zone = found_dict['Z'].lower()
  421. for value, tz_values in enumerate(locale_time.timezone):
  422. if found_zone in tz_values:
  423. # Deal with bad locale setup where timezone names are the
  424. # same and yet time.daylight is true; too ambiguous to
  425. # be able to tell what timezone has daylight savings
  426. if (time.tzname[0] == time.tzname[1] and
  427. time.daylight and found_zone not in ("utc", "gmt")):
  428. break
  429. else:
  430. tz = value
  431. break
  432. # Deal with the cases where ambiguities arise
  433. # don't assume default values for ISO week/year
  434. if year is None and iso_year is not None:
  435. if iso_week is None or weekday is None:
  436. raise ValueError("ISO year directive '%G' must be used with "
  437. "the ISO week directive '%V' and a weekday "
  438. "directive ('%A', '%a', '%w', or '%u').")
  439. if julian is not None:
  440. raise ValueError("Day of the year directive '%j' is not "
  441. "compatible with ISO year directive '%G'. "
  442. "Use '%Y' instead.")
  443. elif week_of_year is None and iso_week is not None:
  444. if weekday is None:
  445. raise ValueError("ISO week directive '%V' must be used with "
  446. "the ISO year directive '%G' and a weekday "
  447. "directive ('%A', '%a', '%w', or '%u').")
  448. else:
  449. raise ValueError("ISO week directive '%V' is incompatible with "
  450. "the year directive '%Y'. Use the ISO year '%G' "
  451. "instead.")
  452. leap_year_fix = False
  453. if year is None and month == 2 and day == 29:
  454. year = 1904 # 1904 is first leap year of 20th century
  455. leap_year_fix = True
  456. elif year is None:
  457. year = 1900
  458. # If we know the week of the year and what day of that week, we can figure
  459. # out the Julian day of the year.
  460. if julian is None and weekday is not None:
  461. if week_of_year is not None:
  462. week_starts_Mon = True if week_of_year_start == 0 else False
  463. julian = _calc_julian_from_U_or_W(year, week_of_year, weekday,
  464. week_starts_Mon)
  465. elif iso_year is not None and iso_week is not None:
  466. datetime_result = datetime_date.fromisocalendar(iso_year, iso_week, weekday + 1)
  467. year = datetime_result.year
  468. month = datetime_result.month
  469. day = datetime_result.day
  470. if julian is not None and julian <= 0:
  471. year -= 1
  472. yday = 366 if calendar.isleap(year) else 365
  473. julian += yday
  474. if julian is None:
  475. # Cannot pre-calculate datetime_date() since can change in Julian
  476. # calculation and thus could have different value for the day of
  477. # the week calculation.
  478. # Need to add 1 to result since first day of the year is 1, not 0.
  479. julian = datetime_date(year, month, day).toordinal() - \
  480. datetime_date(year, 1, 1).toordinal() + 1
  481. else: # Assume that if they bothered to include Julian day (or if it was
  482. # calculated above with year/week/weekday) it will be accurate.
  483. datetime_result = datetime_date.fromordinal(
  484. (julian - 1) +
  485. datetime_date(year, 1, 1).toordinal())
  486. year = datetime_result.year
  487. month = datetime_result.month
  488. day = datetime_result.day
  489. if weekday is None:
  490. weekday = datetime_date(year, month, day).weekday()
  491. # Add timezone info
  492. tzname = found_dict.get("Z")
  493. if leap_year_fix:
  494. # the caller didn't supply a year but asked for Feb 29th. We couldn't
  495. # use the default of 1900 for computations. We set it back to ensure
  496. # that February 29th is smaller than March 1st.
  497. year = 1900
  498. return (year, month, day,
  499. hour, minute, second,
  500. weekday, julian, tz, tzname, gmtoff), fraction, gmtoff_fraction
  501. def _strptime_time(data_string, format="%a %b %d %H:%M:%S %Y"):
  502. """Return a time struct based on the input string and the
  503. format string."""
  504. tt = _strptime(data_string, format)[0]
  505. return time.struct_time(tt[:time._STRUCT_TM_ITEMS])
  506. def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):
  507. """Return a class cls instance based on the input string and the
  508. format string."""
  509. tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  510. tzname, gmtoff = tt[-2:]
  511. args = tt[:6] + (fraction,)
  512. if gmtoff is not None:
  513. tzdelta = datetime_timedelta(seconds=gmtoff, microseconds=gmtoff_fraction)
  514. if tzname:
  515. tz = datetime_timezone(tzdelta, tzname)
  516. else:
  517. tz = datetime_timezone(tzdelta)
  518. args += (tz,)
  519. return cls(*args)