home *** CD-ROM | disk | FTP | other *** search
/ Chip 2011 November / CHIP_2011_11.iso / Programy / Narzedzia / Calibre / calibre-0.8.18.msi / file_262 / _strptime.pyo (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2011-09-09  |  10.7 KB  |  347 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyo (Python 2.7)
  3.  
  4. import time
  5. import locale
  6. import calendar
  7. from re import compile as re_compile
  8. from re import IGNORECASE
  9. from re import escape as re_escape
  10. from datetime import date as datetime_date
  11.  
  12. try:
  13.     from thread import allocate_lock as _thread_allocate_lock
  14. except:
  15.     from dummy_thread import allocate_lock as _thread_allocate_lock
  16.  
  17. __all__ = []
  18.  
  19. def _getlang():
  20.     return locale.getlocale(locale.LC_TIME)
  21.  
  22.  
  23. class LocaleTime(object):
  24.     
  25.     def __init__(self):
  26.         self.lang = _getlang()
  27.         self._LocaleTime__calc_weekday()
  28.         self._LocaleTime__calc_month()
  29.         self._LocaleTime__calc_am_pm()
  30.         self._LocaleTime__calc_timezone()
  31.         self._LocaleTime__calc_date_time()
  32.         if _getlang() != self.lang:
  33.             raise ValueError('locale changed during initialization')
  34.  
  35.     
  36.     def __pad(self, seq, front):
  37.         seq = list(seq)
  38.         if front:
  39.             seq.insert(0, '')
  40.         else:
  41.             seq.append('')
  42.         return seq
  43.  
  44.     
  45.     def __calc_weekday(self):
  46.         a_weekday = [ calendar.day_abbr[i].lower() for i in range(7) ]
  47.         f_weekday = [ calendar.day_name[i].lower() for i in range(7) ]
  48.         self.a_weekday = a_weekday
  49.         self.f_weekday = f_weekday
  50.  
  51.     
  52.     def __calc_month(self):
  53.         a_month = [ calendar.month_abbr[i].lower() for i in range(13) ]
  54.         f_month = [ calendar.month_name[i].lower() for i in range(13) ]
  55.         self.a_month = a_month
  56.         self.f_month = f_month
  57.  
  58.     
  59.     def __calc_am_pm(self):
  60.         am_pm = []
  61.         for hour in (1, 22):
  62.             time_tuple = time.struct_time((1999, 3, 17, hour, 44, 55, 2, 76, 0))
  63.             am_pm.append(time.strftime('%p', time_tuple).lower())
  64.         
  65.         self.am_pm = am_pm
  66.  
  67.     
  68.     def __calc_date_time(self):
  69.         time_tuple = time.struct_time((1999, 3, 17, 22, 44, 55, 2, 76, 0))
  70.         date_time = [
  71.             None,
  72.             None,
  73.             None]
  74.         date_time[0] = time.strftime('%c', time_tuple).lower()
  75.         date_time[1] = time.strftime('%x', time_tuple).lower()
  76.         date_time[2] = time.strftime('%X', time_tuple).lower()
  77.         replacement_pairs = [
  78.             ('%', '%%'),
  79.             (self.f_weekday[2], '%A'),
  80.             (self.f_month[3], '%B'),
  81.             (self.a_weekday[2], '%a'),
  82.             (self.a_month[3], '%b'),
  83.             (self.am_pm[1], '%p'),
  84.             ('1999', '%Y'),
  85.             ('99', '%y'),
  86.             ('22', '%H'),
  87.             ('44', '%M'),
  88.             ('55', '%S'),
  89.             ('76', '%j'),
  90.             ('17', '%d'),
  91.             ('03', '%m'),
  92.             ('3', '%m'),
  93.             ('2', '%w'),
  94.             ('10', '%I')]
  95.         replacement_pairs.extend([ (tz, '%Z') for tz_values in self.timezone for tz in tz_values ])
  96.         for offset, directive in ((0, '%c'), (1, '%x'), (2, '%X')):
  97.             current_format = date_time[offset]
  98.             for old, new in replacement_pairs:
  99.                 if old:
  100.                     current_format = current_format.replace(old, new)
  101.                     continue
  102.             time_tuple = time.struct_time((1999, 1, 3, 1, 1, 1, 6, 3, 0))
  103.             if '00' in time.strftime(directive, time_tuple):
  104.                 U_W = '%W'
  105.             else:
  106.                 U_W = '%U'
  107.             date_time[offset] = current_format.replace('11', U_W)
  108.         
  109.         self.LC_date_time = date_time[0]
  110.         self.LC_date = date_time[1]
  111.         self.LC_time = date_time[2]
  112.  
  113.     
  114.     def __calc_timezone(self):
  115.         
  116.         try:
  117.             time.tzset()
  118.         except AttributeError:
  119.             pass
  120.  
  121.         no_saving = frozenset([
  122.             'utc',
  123.             'gmt',
  124.             time.tzname[0].lower()])
  125.         if time.daylight:
  126.             has_saving = frozenset([
  127.                 time.tzname[1].lower()])
  128.         else:
  129.             has_saving = frozenset()
  130.         self.timezone = (no_saving, has_saving)
  131.  
  132.  
  133.  
  134. class TimeRE(dict):
  135.     
  136.     def __init__(self, locale_time = None):
  137.         if locale_time:
  138.             self.locale_time = locale_time
  139.         else:
  140.             self.locale_time = LocaleTime()
  141.         base = super(TimeRE, self)
  142.         base.__init__({
  143.             'd': '(?P<d>3[0-1]|[1-2]\\d|0[1-9]|[1-9]| [1-9])',
  144.             'f': '(?P<f>[0-9]{1,6})',
  145.             'H': '(?P<H>2[0-3]|[0-1]\\d|\\d)',
  146.             'I': '(?P<I>1[0-2]|0[1-9]|[1-9])',
  147.             'j': '(?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])',
  148.             'm': '(?P<m>1[0-2]|0[1-9]|[1-9])',
  149.             'M': '(?P<M>[0-5]\\d|\\d)',
  150.             'S': '(?P<S>6[0-1]|[0-5]\\d|\\d)',
  151.             'U': '(?P<U>5[0-3]|[0-4]\\d|\\d)',
  152.             'w': '(?P<w>[0-6])',
  153.             'y': '(?P<y>\\d\\d)',
  154.             'Y': '(?P<Y>\\d\\d\\d\\d)',
  155.             'A': self._TimeRE__seqToRE(self.locale_time.f_weekday, 'A'),
  156.             'a': self._TimeRE__seqToRE(self.locale_time.a_weekday, 'a'),
  157.             'B': self._TimeRE__seqToRE(self.locale_time.f_month[1:], 'B'),
  158.             'b': self._TimeRE__seqToRE(self.locale_time.a_month[1:], 'b'),
  159.             'p': self._TimeRE__seqToRE(self.locale_time.am_pm, 'p'),
  160.             'Z': self._TimeRE__seqToRE((lambda .0: pass)(self.locale_time.timezone), 'Z'),
  161.             '%': '%' })
  162.         base.__setitem__('W', base.__getitem__('U').replace('U', 'W'))
  163.         base.__setitem__('c', self.pattern(self.locale_time.LC_date_time))
  164.         base.__setitem__('x', self.pattern(self.locale_time.LC_date))
  165.         base.__setitem__('X', self.pattern(self.locale_time.LC_time))
  166.  
  167.     
  168.     def __seqToRE(self, to_convert, directive):
  169.         to_convert = sorted(to_convert, key = len, reverse = True)
  170.         for value in to_convert:
  171.             if value != '':
  172.                 break
  173.                 continue
  174.             return ''
  175.             regex = '|'.join((lambda .0: pass)(to_convert))
  176.             regex = '(?P<%s>%s' % (directive, regex)
  177.             return '%s)' % regex
  178.  
  179.     
  180.     def pattern(self, format):
  181.         processed_format = ''
  182.         regex_chars = re_compile('([\\\\.^$*+?\\(\\){}\\[\\]|])')
  183.         format = regex_chars.sub('\\\\\\1', format)
  184.         whitespace_replacement = re_compile('\\s+')
  185.         format = whitespace_replacement.sub('\\s+', format)
  186.         while '%' in format:
  187.             directive_index = format.index('%') + 1
  188.             processed_format = '%s%s%s' % (processed_format, format[:directive_index - 1], self[format[directive_index]])
  189.             format = format[directive_index + 1:]
  190.         return '%s%s' % (processed_format, format)
  191.  
  192.     
  193.     def compile(self, format):
  194.         return re_compile(self.pattern(format), IGNORECASE)
  195.  
  196.  
  197. _cache_lock = _thread_allocate_lock()
  198. _TimeRE_cache = TimeRE()
  199. _CACHE_MAX_SIZE = 5
  200. _regex_cache = { }
  201.  
  202. def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon):
  203.     first_weekday = datetime_date(year, 1, 1).weekday()
  204.     if not week_starts_Mon:
  205.         first_weekday = (first_weekday + 1) % 7
  206.         day_of_week = (day_of_week + 1) % 7
  207.     week_0_length = (7 - first_weekday) % 7
  208.     if week_of_year == 0:
  209.         return 1 + day_of_week - first_weekday
  210.     days_to_week = None + 7 * (week_of_year - 1)
  211.     return 1 + days_to_week + day_of_week
  212.  
  213.  
  214. def _strptime(data_string, format = '%a %b %d %H:%M:%S %Y'):
  215.     global _TimeRE_cache
  216.     with _cache_lock:
  217.         if _getlang() != _TimeRE_cache.locale_time.lang:
  218.             _TimeRE_cache = TimeRE()
  219.             _regex_cache.clear()
  220.         if len(_regex_cache) > _CACHE_MAX_SIZE:
  221.             _regex_cache.clear()
  222.         locale_time = _TimeRE_cache.locale_time
  223.         format_regex = _regex_cache.get(format)
  224.         if not format_regex:
  225.             
  226.             try:
  227.                 format_regex = _TimeRE_cache.compile(format)
  228.             except KeyError:
  229.                 err = None
  230.                 bad_directive = err.args[0]
  231.                 if bad_directive == '\\':
  232.                     bad_directive = '%'
  233.                 del err
  234.                 raise ValueError("'%s' is a bad directive in format '%s'" % (bad_directive, format))
  235.             except IndexError:
  236.                 raise ValueError("stray %% in format '%s'" % format)
  237.  
  238.             _regex_cache[format] = format_regex
  239.     found = format_regex.match(data_string)
  240.     if not found:
  241.         raise ValueError('time data %r does not match format %r' % (data_string, format))
  242.     if len(data_string) != found.end():
  243.         raise ValueError('unconverted data remains: %s' % data_string[found.end():])
  244.     year = 1900
  245.     month = day = 1
  246.     hour = minute = second = fraction = 0
  247.     tz = -1
  248.     week_of_year = -1
  249.     week_of_year_start = -1
  250.     weekday = julian = -1
  251.     found_dict = found.groupdict()
  252.     for group_key in found_dict.iterkeys():
  253.         if group_key == 'y':
  254.             year = int(found_dict['y'])
  255.             if year <= 68:
  256.                 year += 2000
  257.             else:
  258.                 year += 1900
  259.         if group_key == 'Y':
  260.             year = int(found_dict['Y'])
  261.             continue
  262.         if group_key == 'm':
  263.             month = int(found_dict['m'])
  264.             continue
  265.         if group_key == 'B':
  266.             month = locale_time.f_month.index(found_dict['B'].lower())
  267.             continue
  268.         if group_key == 'b':
  269.             month = locale_time.a_month.index(found_dict['b'].lower())
  270.             continue
  271.         if group_key == 'd':
  272.             day = int(found_dict['d'])
  273.             continue
  274.         if group_key == 'H':
  275.             hour = int(found_dict['H'])
  276.             continue
  277.         if group_key == 'I':
  278.             hour = int(found_dict['I'])
  279.             ampm = found_dict.get('p', '').lower()
  280.             if ampm in ('', locale_time.am_pm[0]) or hour == 12:
  281.                 hour = 0
  282.             
  283.         elif ampm == locale_time.am_pm[1]:
  284.             if hour != 12:
  285.                 hour += 12
  286.             
  287.         
  288.         if group_key == 'M':
  289.             minute = int(found_dict['M'])
  290.             continue
  291.         if group_key == 'S':
  292.             second = int(found_dict['S'])
  293.             continue
  294.         if group_key == 'f':
  295.             s = found_dict['f']
  296.             s += '0' * (6 - len(s))
  297.             fraction = int(s)
  298.             continue
  299.         if group_key == 'A':
  300.             weekday = locale_time.f_weekday.index(found_dict['A'].lower())
  301.             continue
  302.         if group_key == 'a':
  303.             weekday = locale_time.a_weekday.index(found_dict['a'].lower())
  304.             continue
  305.         if group_key == 'w':
  306.             weekday = int(found_dict['w'])
  307.             if weekday == 0:
  308.                 weekday = 6
  309.             else:
  310.                 weekday -= 1
  311.         if group_key == 'j':
  312.             julian = int(found_dict['j'])
  313.             continue
  314.         if group_key in ('U', 'W'):
  315.             week_of_year = int(found_dict[group_key])
  316.             if group_key == 'U':
  317.                 week_of_year_start = 6
  318.             else:
  319.                 week_of_year_start = 0
  320.         if group_key == 'Z':
  321.             found_zone = found_dict['Z'].lower()
  322.             for value, tz_values in enumerate(locale_time.timezone):
  323.                 if (found_zone in tz_values or time.tzname[0] == time.tzname[1]) and time.daylight and found_zone not in ('utc', 'gmt'):
  324.                     break
  325.                 else:
  326.                     tz = value
  327.                     break
  328.             
  329.     if julian == -1 and week_of_year != -1 and weekday != -1:
  330.         week_starts_Mon = True if week_of_year_start == 0 else False
  331.         julian = _calc_julian_from_U_or_W(year, week_of_year, weekday, week_starts_Mon)
  332.     if julian == -1:
  333.         julian = (datetime_date(year, month, day).toordinal() - datetime_date(year, 1, 1).toordinal()) + 1
  334.     else:
  335.         datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal())
  336.         year = datetime_result.year
  337.         month = datetime_result.month
  338.         day = datetime_result.day
  339.     if weekday == -1:
  340.         weekday = datetime_date(year, month, day).weekday()
  341.     return (time.struct_time((year, month, day, hour, minute, second, weekday, julian, tz)), fraction)
  342.  
  343.  
  344. def _strptime_time(data_string, format = '%a %b %d %H:%M:%S %Y'):
  345.     return _strptime(data_string, format)[0]
  346.  
  347.