PageRenderTime 47ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/_strptime.py

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