_strptime.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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. try:
  20. from _thread import allocate_lock as _thread_allocate_lock
  21. except ImportError:
  22. from _dummy_thread import allocate_lock as _thread_allocate_lock
  23. __all__ = []
  24. def _getlang():
  25. # Figure out what the current language is set to.
  26. return locale.getlocale(locale.LC_TIME)
  27. class LocaleTime(object):
  28. """Stores and handles locale-specific information related to time.
  29. ATTRIBUTES:
  30. f_weekday -- full weekday names (7-item list)
  31. a_weekday -- abbreviated weekday names (7-item list)
  32. f_month -- full month names (13-item list; dummy value in [0], which
  33. is added by code)
  34. a_month -- abbreviated month names (13-item list, dummy value in
  35. [0], which is added by code)
  36. am_pm -- AM/PM representation (2-item list)
  37. LC_date_time -- format string for date/time representation (string)
  38. LC_date -- format string for date representation (string)
  39. LC_time -- format string for time representation (string)
  40. timezone -- daylight- and non-daylight-savings timezone representation
  41. (2-item list of sets)
  42. lang -- Language used by instance (2-item tuple)
  43. """
  44. def __init__(self):
  45. """Set all attributes.
  46. Order of methods called matters for dependency reasons.
  47. The locale language is set at the offset and then checked again before
  48. exiting. This is to make sure that the attributes were not set with a
  49. mix of information from more than one locale. This would most likely
  50. happen when using threads where one thread calls a locale-dependent
  51. function while another thread changes the locale while the function in
  52. the other thread is still running. Proper coding would call for
  53. locks to prevent changing the locale while locale-dependent code is
  54. running. The check here is done in case someone does not think about
  55. doing this.
  56. Only other possible issue is if someone changed the timezone and did
  57. not call tz.tzset . That is an issue for the programmer, though,
  58. since changing the timezone is worthless without that call.
  59. """
  60. self.lang = _getlang()
  61. self.__calc_weekday()
  62. self.__calc_month()
  63. self.__calc_am_pm()
  64. self.__calc_timezone()
  65. self.__calc_date_time()
  66. if _getlang() != self.lang:
  67. raise ValueError("locale changed during initialization")
  68. if time.tzname != self.tzname or time.daylight != self.daylight:
  69. raise ValueError("timezone changed during initialization")
  70. def __pad(self, seq, front):
  71. # Add '' to seq to either the front (is True), else the back.
  72. seq = list(seq)
  73. if front:
  74. seq.insert(0, '')
  75. else:
  76. seq.append('')
  77. return seq
  78. def __calc_weekday(self):
  79. # Set self.a_weekday and self.f_weekday using the calendar
  80. # module.
  81. a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]
  82. f_weekday = [calendar.day_name[i].lower() for i in range(7)]
  83. self.a_weekday = a_weekday
  84. self.f_weekday = f_weekday
  85. def __calc_month(self):
  86. # Set self.f_month and self.a_month using the calendar module.
  87. a_month = [calendar.month_abbr[i].lower() for i in range(13)]
  88. f_month = [calendar.month_name[i].lower() for i in range(13)]
  89. self.a_month = a_month
  90. self.f_month = f_month
  91. def __calc_am_pm(self):
  92. # Set self.am_pm by using time.strftime().
  93. # The magic date (1999,3,17,hour,44,55,2,76,0) is not really that
  94. # magical; just happened to have used it everywhere else where a
  95. # static date was needed.
  96. am_pm = []
  97. for hour in (1, 22):
  98. time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0))
  99. am_pm.append(time.strftime("%p", time_tuple).lower())
  100. self.am_pm = am_pm
  101. def __calc_date_time(self):
  102. # Set self.date_time, self.date, & self.time by using
  103. # time.strftime().
  104. # Use (1999,3,17,22,44,55,2,76,0) for magic date because the amount of
  105. # overloaded numbers is minimized. The order in which searches for
  106. # values within the format string is very important; it eliminates
  107. # possible ambiguity for what something represents.
  108. time_tuple = time.struct_time((1999,3,17,22,44,55,2,76,0))
  109. date_time = [None, None, None]
  110. date_time[0] = time.strftime("%c", time_tuple).lower()
  111. date_time[1] = time.strftime("%x", time_tuple).lower()
  112. date_time[2] = time.strftime("%X", time_tuple).lower()
  113. replacement_pairs = [('%', '%%'), (self.f_weekday[2], '%A'),
  114. (self.f_month[3], '%B'), (self.a_weekday[2], '%a'),
  115. (self.a_month[3], '%b'), (self.am_pm[1], '%p'),
  116. ('1999', '%Y'), ('99', '%y'), ('22', '%H'),
  117. ('44', '%M'), ('55', '%S'), ('76', '%j'),
  118. ('17', '%d'), ('03', '%m'), ('3', '%m'),
  119. # '3' needed for when no leading zero.
  120. ('2', '%w'), ('10', '%I')]
  121. replacement_pairs.extend([(tz, "%Z") for tz_values in self.timezone
  122. for tz in tz_values])
  123. for offset,directive in ((0,'%c'), (1,'%x'), (2,'%X')):
  124. current_format = date_time[offset]
  125. for old, new in replacement_pairs:
  126. # Must deal with possible lack of locale info
  127. # manifesting itself as the empty string (e.g., Swedish's
  128. # lack of AM/PM info) or a platform returning a tuple of empty
  129. # strings (e.g., MacOS 9 having timezone as ('','')).
  130. if old:
  131. current_format = current_format.replace(old, new)
  132. # If %W is used, then Sunday, 2005-01-03 will fall on week 0 since
  133. # 2005-01-03 occurs before the first Monday of the year. Otherwise
  134. # %U is used.
  135. time_tuple = time.struct_time((1999,1,3,1,1,1,6,3,0))
  136. if '00' in time.strftime(directive, time_tuple):
  137. U_W = '%W'
  138. else:
  139. U_W = '%U'
  140. date_time[offset] = current_format.replace('11', U_W)
  141. self.LC_date_time = date_time[0]
  142. self.LC_date = date_time[1]
  143. self.LC_time = date_time[2]
  144. def __calc_timezone(self):
  145. # Set self.timezone by using time.tzname.
  146. # Do not worry about possibility of time.tzname[0] == time.tzname[1]
  147. # and time.daylight; handle that in strptime.
  148. try:
  149. time.tzset()
  150. except AttributeError:
  151. pass
  152. self.tzname = time.tzname
  153. self.daylight = time.daylight
  154. no_saving = frozenset({"utc", "gmt", self.tzname[0].lower()})
  155. if self.daylight:
  156. has_saving = frozenset({self.tzname[1].lower()})
  157. else:
  158. has_saving = frozenset()
  159. self.timezone = (no_saving, has_saving)
  160. class TimeRE(dict):
  161. """Handle conversion from format directives to regexes."""
  162. def __init__(self, locale_time=None):
  163. """Create keys/values.
  164. Order of execution is important for dependency reasons.
  165. """
  166. if locale_time:
  167. self.locale_time = locale_time
  168. else:
  169. self.locale_time = LocaleTime()
  170. base = super()
  171. base.__init__({
  172. # The " \d" part of the regex is to make %c from ANSI C work
  173. 'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])",
  174. 'f': r"(?P<f>[0-9]{1,6})",
  175. 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)",
  176. 'I': r"(?P<I>1[0-2]|0[1-9]|[1-9])",
  177. '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])",
  178. 'm': r"(?P<m>1[0-2]|0[1-9]|[1-9])",
  179. 'M': r"(?P<M>[0-5]\d|\d)",
  180. 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)",
  181. 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)",
  182. 'w': r"(?P<w>[0-6])",
  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)",
  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 _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
  267. """Return a 2-tuple consisting of a time struct and an int containing
  268. the number of microseconds based on the input string and the
  269. format string."""
  270. for index, arg in enumerate([data_string, format]):
  271. if not isinstance(arg, str):
  272. msg = "strptime() argument {} must be str, not {}"
  273. raise TypeError(msg.format(index, type(arg)))
  274. global _TimeRE_cache, _regex_cache
  275. with _cache_lock:
  276. locale_time = _TimeRE_cache.locale_time
  277. if (_getlang() != locale_time.lang or
  278. time.tzname != locale_time.tzname or
  279. time.daylight != locale_time.daylight):
  280. _TimeRE_cache = TimeRE()
  281. _regex_cache.clear()
  282. locale_time = _TimeRE_cache.locale_time
  283. if len(_regex_cache) > _CACHE_MAX_SIZE:
  284. _regex_cache.clear()
  285. format_regex = _regex_cache.get(format)
  286. if not format_regex:
  287. try:
  288. format_regex = _TimeRE_cache.compile(format)
  289. # KeyError raised when a bad format is found; can be specified as
  290. # \\, in which case it was a stray % but with a space after it
  291. except KeyError as err:
  292. bad_directive = err.args[0]
  293. if bad_directive == "\\":
  294. bad_directive = "%"
  295. del err
  296. raise ValueError("'%s' is a bad directive in format '%s'" %
  297. (bad_directive, format)) from None
  298. # IndexError only occurs when the format string is "%"
  299. except IndexError:
  300. raise ValueError("stray %% in format '%s'" % format) from None
  301. _regex_cache[format] = format_regex
  302. found = format_regex.match(data_string)
  303. if not found:
  304. raise ValueError("time data %r does not match format %r" %
  305. (data_string, format))
  306. if len(data_string) != found.end():
  307. raise ValueError("unconverted data remains: %s" %
  308. data_string[found.end():])
  309. year = None
  310. month = day = 1
  311. hour = minute = second = fraction = 0
  312. tz = -1
  313. tzoffset = None
  314. # Default to -1 to signify that values not known; not critical to have,
  315. # though
  316. week_of_year = -1
  317. week_of_year_start = -1
  318. # weekday and julian defaulted to None so as to signal need to calculate
  319. # values
  320. weekday = julian = None
  321. found_dict = found.groupdict()
  322. for group_key in found_dict.keys():
  323. # Directives not explicitly handled below:
  324. # c, x, X
  325. # handled by making out of other directives
  326. # U, W
  327. # worthless without day of the week
  328. if group_key == 'y':
  329. year = int(found_dict['y'])
  330. # Open Group specification for strptime() states that a %y
  331. #value in the range of [00, 68] is in the century 2000, while
  332. #[69,99] is in the century 1900
  333. if year <= 68:
  334. year += 2000
  335. else:
  336. year += 1900
  337. elif group_key == 'Y':
  338. year = int(found_dict['Y'])
  339. elif group_key == 'm':
  340. month = int(found_dict['m'])
  341. elif group_key == 'B':
  342. month = locale_time.f_month.index(found_dict['B'].lower())
  343. elif group_key == 'b':
  344. month = locale_time.a_month.index(found_dict['b'].lower())
  345. elif group_key == 'd':
  346. day = int(found_dict['d'])
  347. elif group_key == 'H':
  348. hour = int(found_dict['H'])
  349. elif group_key == 'I':
  350. hour = int(found_dict['I'])
  351. ampm = found_dict.get('p', '').lower()
  352. # If there was no AM/PM indicator, we'll treat this like AM
  353. if ampm in ('', locale_time.am_pm[0]):
  354. # We're in AM so the hour is correct unless we're
  355. # looking at 12 midnight.
  356. # 12 midnight == 12 AM == hour 0
  357. if hour == 12:
  358. hour = 0
  359. elif ampm == locale_time.am_pm[1]:
  360. # We're in PM so we need to add 12 to the hour unless
  361. # we're looking at 12 noon.
  362. # 12 noon == 12 PM == hour 12
  363. if hour != 12:
  364. hour += 12
  365. elif group_key == 'M':
  366. minute = int(found_dict['M'])
  367. elif group_key == 'S':
  368. second = int(found_dict['S'])
  369. elif group_key == 'f':
  370. s = found_dict['f']
  371. # Pad to always return microseconds.
  372. s += "0" * (6 - len(s))
  373. fraction = int(s)
  374. elif group_key == 'A':
  375. weekday = locale_time.f_weekday.index(found_dict['A'].lower())
  376. elif group_key == 'a':
  377. weekday = locale_time.a_weekday.index(found_dict['a'].lower())
  378. elif group_key == 'w':
  379. weekday = int(found_dict['w'])
  380. if weekday == 0:
  381. weekday = 6
  382. else:
  383. weekday -= 1
  384. elif group_key == 'j':
  385. julian = int(found_dict['j'])
  386. elif group_key in ('U', 'W'):
  387. week_of_year = int(found_dict[group_key])
  388. if group_key == 'U':
  389. # U starts week on Sunday.
  390. week_of_year_start = 6
  391. else:
  392. # W starts week on Monday.
  393. week_of_year_start = 0
  394. elif group_key == 'z':
  395. z = found_dict['z']
  396. tzoffset = int(z[1:3]) * 60 + int(z[3:5])
  397. if z.startswith("-"):
  398. tzoffset = -tzoffset
  399. elif group_key == 'Z':
  400. # Since -1 is default value only need to worry about setting tz if
  401. # it can be something other than -1.
  402. found_zone = found_dict['Z'].lower()
  403. for value, tz_values in enumerate(locale_time.timezone):
  404. if found_zone in tz_values:
  405. # Deal with bad locale setup where timezone names are the
  406. # same and yet time.daylight is true; too ambiguous to
  407. # be able to tell what timezone has daylight savings
  408. if (time.tzname[0] == time.tzname[1] and
  409. time.daylight and found_zone not in ("utc", "gmt")):
  410. break
  411. else:
  412. tz = value
  413. break
  414. leap_year_fix = False
  415. if year is None and month == 2 and day == 29:
  416. year = 1904 # 1904 is first leap year of 20th century
  417. leap_year_fix = True
  418. elif year is None:
  419. year = 1900
  420. # If we know the week of the year and what day of that week, we can figure
  421. # out the Julian day of the year.
  422. if julian is None and week_of_year != -1 and weekday is not None:
  423. week_starts_Mon = True if week_of_year_start == 0 else False
  424. julian = _calc_julian_from_U_or_W(year, week_of_year, weekday,
  425. week_starts_Mon)
  426. if julian <= 0:
  427. year -= 1
  428. yday = 366 if calendar.isleap(year) else 365
  429. julian += yday
  430. # Cannot pre-calculate datetime_date() since can change in Julian
  431. # calculation and thus could have different value for the day of the week
  432. # calculation.
  433. if julian is None:
  434. # Need to add 1 to result since first day of the year is 1, not 0.
  435. julian = datetime_date(year, month, day).toordinal() - \
  436. datetime_date(year, 1, 1).toordinal() + 1
  437. else: # Assume that if they bothered to include Julian day it will
  438. # be accurate.
  439. datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal())
  440. year = datetime_result.year
  441. month = datetime_result.month
  442. day = datetime_result.day
  443. if weekday is None:
  444. weekday = datetime_date(year, month, day).weekday()
  445. # Add timezone info
  446. tzname = found_dict.get("Z")
  447. if tzoffset is not None:
  448. gmtoff = tzoffset * 60
  449. else:
  450. gmtoff = None
  451. if leap_year_fix:
  452. # the caller didn't supply a year but asked for Feb 29th. We couldn't
  453. # use the default of 1900 for computations. We set it back to ensure
  454. # that February 29th is smaller than March 1st.
  455. year = 1900
  456. return (year, month, day,
  457. hour, minute, second,
  458. weekday, julian, tz, tzname, gmtoff), fraction
  459. def _strptime_time(data_string, format="%a %b %d %H:%M:%S %Y"):
  460. """Return a time struct based on the input string and the
  461. format string."""
  462. tt = _strptime(data_string, format)[0]
  463. return time.struct_time(tt[:time._STRUCT_TM_ITEMS])
  464. def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):
  465. """Return a class cls instance based on the input string and the
  466. format string."""
  467. tt, fraction = _strptime(data_string, format)
  468. tzname, gmtoff = tt[-2:]
  469. args = tt[:6] + (fraction,)
  470. if gmtoff is not None:
  471. tzdelta = datetime_timedelta(seconds=gmtoff)
  472. if tzname:
  473. tz = datetime_timezone(tzdelta, tzname)
  474. else:
  475. tz = datetime_timezone(tzdelta)
  476. args += (tz,)
  477. return cls(*args)