_strptime.py 24 KB

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