_strptime.py 25 KB

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