+++ /dev/null
-"""Strptime-related classes and functions.\r
-\r
-CLASSES:\r
- LocaleTime -- Discovers and stores locale-specific time information\r
- TimeRE -- Creates regexes for pattern matching a string of text containing\r
- time information\r
-\r
-FUNCTIONS:\r
- _getlang -- Figure out what language is being used for the locale\r
- strptime -- Calculates the time struct represented by the passed-in string\r
-\r
-"""\r
-import time\r
-import locale\r
-import calendar\r
-from re import compile as re_compile\r
-from re import IGNORECASE\r
-from re import escape as re_escape\r
-from datetime import date as datetime_date\r
-try:\r
- from thread import allocate_lock as _thread_allocate_lock\r
-except:\r
- from dummy_thread import allocate_lock as _thread_allocate_lock\r
-\r
-__all__ = []\r
-\r
-def _getlang():\r
- # Figure out what the current language is set to.\r
- return locale.getlocale(locale.LC_TIME)\r
-\r
-class LocaleTime(object):\r
- """Stores and handles locale-specific information related to time.\r
-\r
- ATTRIBUTES:\r
- f_weekday -- full weekday names (7-item list)\r
- a_weekday -- abbreviated weekday names (7-item list)\r
- f_month -- full month names (13-item list; dummy value in [0], which\r
- is added by code)\r
- a_month -- abbreviated month names (13-item list, dummy value in\r
- [0], which is added by code)\r
- am_pm -- AM/PM representation (2-item list)\r
- LC_date_time -- format string for date/time representation (string)\r
- LC_date -- format string for date representation (string)\r
- LC_time -- format string for time representation (string)\r
- timezone -- daylight- and non-daylight-savings timezone representation\r
- (2-item list of sets)\r
- lang -- Language used by instance (2-item tuple)\r
- """\r
-\r
- def __init__(self):\r
- """Set all attributes.\r
-\r
- Order of methods called matters for dependency reasons.\r
-\r
- The locale language is set at the offset and then checked again before\r
- exiting. This is to make sure that the attributes were not set with a\r
- mix of information from more than one locale. This would most likely\r
- happen when using threads where one thread calls a locale-dependent\r
- function while another thread changes the locale while the function in\r
- the other thread is still running. Proper coding would call for\r
- locks to prevent changing the locale while locale-dependent code is\r
- running. The check here is done in case someone does not think about\r
- doing this.\r
-\r
- Only other possible issue is if someone changed the timezone and did\r
- not call tz.tzset . That is an issue for the programmer, though,\r
- since changing the timezone is worthless without that call.\r
-\r
- """\r
- self.lang = _getlang()\r
- self.__calc_weekday()\r
- self.__calc_month()\r
- self.__calc_am_pm()\r
- self.__calc_timezone()\r
- self.__calc_date_time()\r
- if _getlang() != self.lang:\r
- raise ValueError("locale changed during initialization")\r
-\r
- def __pad(self, seq, front):\r
- # Add '' to seq to either the front (is True), else the back.\r
- seq = list(seq)\r
- if front:\r
- seq.insert(0, '')\r
- else:\r
- seq.append('')\r
- return seq\r
-\r
- def __calc_weekday(self):\r
- # Set self.a_weekday and self.f_weekday using the calendar\r
- # module.\r
- a_weekday = [calendar.day_abbr[i].lower() for i in range(7)]\r
- f_weekday = [calendar.day_name[i].lower() for i in range(7)]\r
- self.a_weekday = a_weekday\r
- self.f_weekday = f_weekday\r
-\r
- def __calc_month(self):\r
- # Set self.f_month and self.a_month using the calendar module.\r
- a_month = [calendar.month_abbr[i].lower() for i in range(13)]\r
- f_month = [calendar.month_name[i].lower() for i in range(13)]\r
- self.a_month = a_month\r
- self.f_month = f_month\r
-\r
- def __calc_am_pm(self):\r
- # Set self.am_pm by using time.strftime().\r
-\r
- # The magic date (1999,3,17,hour,44,55,2,76,0) is not really that\r
- # magical; just happened to have used it everywhere else where a\r
- # static date was needed.\r
- am_pm = []\r
- for hour in (01,22):\r
- time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0))\r
- am_pm.append(time.strftime("%p", time_tuple).lower())\r
- self.am_pm = am_pm\r
-\r
- def __calc_date_time(self):\r
- # Set self.date_time, self.date, & self.time by using\r
- # time.strftime().\r
-\r
- # Use (1999,3,17,22,44,55,2,76,0) for magic date because the amount of\r
- # overloaded numbers is minimized. The order in which searches for\r
- # values within the format string is very important; it eliminates\r
- # possible ambiguity for what something represents.\r
- time_tuple = time.struct_time((1999,3,17,22,44,55,2,76,0))\r
- date_time = [None, None, None]\r
- date_time[0] = time.strftime("%c", time_tuple).lower()\r
- date_time[1] = time.strftime("%x", time_tuple).lower()\r
- date_time[2] = time.strftime("%X", time_tuple).lower()\r
- replacement_pairs = [('%', '%%'), (self.f_weekday[2], '%A'),\r
- (self.f_month[3], '%B'), (self.a_weekday[2], '%a'),\r
- (self.a_month[3], '%b'), (self.am_pm[1], '%p'),\r
- ('1999', '%Y'), ('99', '%y'), ('22', '%H'),\r
- ('44', '%M'), ('55', '%S'), ('76', '%j'),\r
- ('17', '%d'), ('03', '%m'), ('3', '%m'),\r
- # '3' needed for when no leading zero.\r
- ('2', '%w'), ('10', '%I')]\r
- replacement_pairs.extend([(tz, "%Z") for tz_values in self.timezone\r
- for tz in tz_values])\r
- for offset,directive in ((0,'%c'), (1,'%x'), (2,'%X')):\r
- current_format = date_time[offset]\r
- for old, new in replacement_pairs:\r
- # Must deal with possible lack of locale info\r
- # manifesting itself as the empty string (e.g., Swedish's\r
- # lack of AM/PM info) or a platform returning a tuple of empty\r
- # strings (e.g., MacOS 9 having timezone as ('','')).\r
- if old:\r
- current_format = current_format.replace(old, new)\r
- # If %W is used, then Sunday, 2005-01-03 will fall on week 0 since\r
- # 2005-01-03 occurs before the first Monday of the year. Otherwise\r
- # %U is used.\r
- time_tuple = time.struct_time((1999,1,3,1,1,1,6,3,0))\r
- if '00' in time.strftime(directive, time_tuple):\r
- U_W = '%W'\r
- else:\r
- U_W = '%U'\r
- date_time[offset] = current_format.replace('11', U_W)\r
- self.LC_date_time = date_time[0]\r
- self.LC_date = date_time[1]\r
- self.LC_time = date_time[2]\r
-\r
- def __calc_timezone(self):\r
- # Set self.timezone by using time.tzname.\r
- # Do not worry about possibility of time.tzname[0] == timetzname[1]\r
- # and time.daylight; handle that in strptime .\r
- try:\r
- time.tzset()\r
- except AttributeError:\r
- pass\r
- no_saving = frozenset(["utc", "gmt", time.tzname[0].lower()])\r
- if time.daylight:\r
- has_saving = frozenset([time.tzname[1].lower()])\r
- else:\r
- has_saving = frozenset()\r
- self.timezone = (no_saving, has_saving)\r
-\r
-\r
-class TimeRE(dict):\r
- """Handle conversion from format directives to regexes."""\r
-\r
- def __init__(self, locale_time=None):\r
- """Create keys/values.\r
-\r
- Order of execution is important for dependency reasons.\r
-\r
- """\r
- if locale_time:\r
- self.locale_time = locale_time\r
- else:\r
- self.locale_time = LocaleTime()\r
- base = super(TimeRE, self)\r
- base.__init__({\r
- # The " \d" part of the regex is to make %c from ANSI C work\r
- 'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])",\r
- 'f': r"(?P<f>[0-9]{1,6})",\r
- 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)",\r
- 'I': r"(?P<I>1[0-2]|0[1-9]|[1-9])",\r
- '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])",\r
- 'm': r"(?P<m>1[0-2]|0[1-9]|[1-9])",\r
- 'M': r"(?P<M>[0-5]\d|\d)",\r
- 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)",\r
- 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)",\r
- 'w': r"(?P<w>[0-6])",\r
- # W is set below by using 'U'\r
- 'y': r"(?P<y>\d\d)",\r
- #XXX: Does 'Y' need to worry about having less or more than\r
- # 4 digits?\r
- 'Y': r"(?P<Y>\d\d\d\d)",\r
- 'A': self.__seqToRE(self.locale_time.f_weekday, 'A'),\r
- 'a': self.__seqToRE(self.locale_time.a_weekday, 'a'),\r
- 'B': self.__seqToRE(self.locale_time.f_month[1:], 'B'),\r
- 'b': self.__seqToRE(self.locale_time.a_month[1:], 'b'),\r
- 'p': self.__seqToRE(self.locale_time.am_pm, 'p'),\r
- 'Z': self.__seqToRE((tz for tz_names in self.locale_time.timezone\r
- for tz in tz_names),\r
- 'Z'),\r
- '%': '%'})\r
- base.__setitem__('W', base.__getitem__('U').replace('U', 'W'))\r
- base.__setitem__('c', self.pattern(self.locale_time.LC_date_time))\r
- base.__setitem__('x', self.pattern(self.locale_time.LC_date))\r
- base.__setitem__('X', self.pattern(self.locale_time.LC_time))\r
-\r
- def __seqToRE(self, to_convert, directive):\r
- """Convert a list to a regex string for matching a directive.\r
-\r
- Want possible matching values to be from longest to shortest. This\r
- prevents the possibility of a match occuring for a value that also\r
- a substring of a larger value that should have matched (e.g., 'abc'\r
- matching when 'abcdef' should have been the match).\r
-\r
- """\r
- to_convert = sorted(to_convert, key=len, reverse=True)\r
- for value in to_convert:\r
- if value != '':\r
- break\r
- else:\r
- return ''\r
- regex = '|'.join(re_escape(stuff) for stuff in to_convert)\r
- regex = '(?P<%s>%s' % (directive, regex)\r
- return '%s)' % regex\r
-\r
- def pattern(self, format):\r
- """Return regex pattern for the format string.\r
-\r
- Need to make sure that any characters that might be interpreted as\r
- regex syntax are escaped.\r
-\r
- """\r
- processed_format = ''\r
- # The sub() call escapes all characters that might be misconstrued\r
- # as regex syntax. Cannot use re.escape since we have to deal with\r
- # format directives (%m, etc.).\r
- regex_chars = re_compile(r"([\\.^$*+?\(\){}\[\]|])")\r
- format = regex_chars.sub(r"\\\1", format)\r
- whitespace_replacement = re_compile('\s+')\r
- format = whitespace_replacement.sub('\s+', format)\r
- while '%' in format:\r
- directive_index = format.index('%')+1\r
- processed_format = "%s%s%s" % (processed_format,\r
- format[:directive_index-1],\r
- self[format[directive_index]])\r
- format = format[directive_index+1:]\r
- return "%s%s" % (processed_format, format)\r
-\r
- def compile(self, format):\r
- """Return a compiled re object for the format string."""\r
- return re_compile(self.pattern(format), IGNORECASE)\r
-\r
-_cache_lock = _thread_allocate_lock()\r
-# DO NOT modify _TimeRE_cache or _regex_cache without acquiring the cache lock\r
-# first!\r
-_TimeRE_cache = TimeRE()\r
-_CACHE_MAX_SIZE = 5 # Max number of regexes stored in _regex_cache\r
-_regex_cache = {}\r
-\r
-def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon):\r
- """Calculate the Julian day based on the year, week of the year, and day of\r
- the week, with week_start_day representing whether the week of the year\r
- assumes the week starts on Sunday or Monday (6 or 0)."""\r
- first_weekday = datetime_date(year, 1, 1).weekday()\r
- # If we are dealing with the %U directive (week starts on Sunday), it's\r
- # easier to just shift the view to Sunday being the first day of the\r
- # week.\r
- if not week_starts_Mon:\r
- first_weekday = (first_weekday + 1) % 7\r
- day_of_week = (day_of_week + 1) % 7\r
- # Need to watch out for a week 0 (when the first day of the year is not\r
- # the same as that specified by %U or %W).\r
- week_0_length = (7 - first_weekday) % 7\r
- if week_of_year == 0:\r
- return 1 + day_of_week - first_weekday\r
- else:\r
- days_to_week = week_0_length + (7 * (week_of_year - 1))\r
- return 1 + days_to_week + day_of_week\r
-\r
-\r
-def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):\r
- """Return a time struct based on the input string and the format string."""\r
- global _TimeRE_cache, _regex_cache\r
- with _cache_lock:\r
- if _getlang() != _TimeRE_cache.locale_time.lang:\r
- _TimeRE_cache = TimeRE()\r
- _regex_cache.clear()\r
- if len(_regex_cache) > _CACHE_MAX_SIZE:\r
- _regex_cache.clear()\r
- locale_time = _TimeRE_cache.locale_time\r
- format_regex = _regex_cache.get(format)\r
- if not format_regex:\r
- try:\r
- format_regex = _TimeRE_cache.compile(format)\r
- # KeyError raised when a bad format is found; can be specified as\r
- # \\, in which case it was a stray % but with a space after it\r
- except KeyError, err:\r
- bad_directive = err.args[0]\r
- if bad_directive == "\\":\r
- bad_directive = "%"\r
- del err\r
- raise ValueError("'%s' is a bad directive in format '%s'" %\r
- (bad_directive, format))\r
- # IndexError only occurs when the format string is "%"\r
- except IndexError:\r
- raise ValueError("stray %% in format '%s'" % format)\r
- _regex_cache[format] = format_regex\r
- found = format_regex.match(data_string)\r
- if not found:\r
- raise ValueError("time data %r does not match format %r" %\r
- (data_string, format))\r
- if len(data_string) != found.end():\r
- raise ValueError("unconverted data remains: %s" %\r
- data_string[found.end():])\r
- year = 1900\r
- month = day = 1\r
- hour = minute = second = fraction = 0\r
- tz = -1\r
- # Default to -1 to signify that values not known; not critical to have,\r
- # though\r
- week_of_year = -1\r
- week_of_year_start = -1\r
- # weekday and julian defaulted to -1 so as to signal need to calculate\r
- # values\r
- weekday = julian = -1\r
- found_dict = found.groupdict()\r
- for group_key in found_dict.iterkeys():\r
- # Directives not explicitly handled below:\r
- # c, x, X\r
- # handled by making out of other directives\r
- # U, W\r
- # worthless without day of the week\r
- if group_key == 'y':\r
- year = int(found_dict['y'])\r
- # Open Group specification for strptime() states that a %y\r
- #value in the range of [00, 68] is in the century 2000, while\r
- #[69,99] is in the century 1900\r
- if year <= 68:\r
- year += 2000\r
- else:\r
- year += 1900\r
- elif group_key == 'Y':\r
- year = int(found_dict['Y'])\r
- elif group_key == 'm':\r
- month = int(found_dict['m'])\r
- elif group_key == 'B':\r
- month = locale_time.f_month.index(found_dict['B'].lower())\r
- elif group_key == 'b':\r
- month = locale_time.a_month.index(found_dict['b'].lower())\r
- elif group_key == 'd':\r
- day = int(found_dict['d'])\r
- elif group_key == 'H':\r
- hour = int(found_dict['H'])\r
- elif group_key == 'I':\r
- hour = int(found_dict['I'])\r
- ampm = found_dict.get('p', '').lower()\r
- # If there was no AM/PM indicator, we'll treat this like AM\r
- if ampm in ('', locale_time.am_pm[0]):\r
- # We're in AM so the hour is correct unless we're\r
- # looking at 12 midnight.\r
- # 12 midnight == 12 AM == hour 0\r
- if hour == 12:\r
- hour = 0\r
- elif ampm == locale_time.am_pm[1]:\r
- # We're in PM so we need to add 12 to the hour unless\r
- # we're looking at 12 noon.\r
- # 12 noon == 12 PM == hour 12\r
- if hour != 12:\r
- hour += 12\r
- elif group_key == 'M':\r
- minute = int(found_dict['M'])\r
- elif group_key == 'S':\r
- second = int(found_dict['S'])\r
- elif group_key == 'f':\r
- s = found_dict['f']\r
- # Pad to always return microseconds.\r
- s += "0" * (6 - len(s))\r
- fraction = int(s)\r
- elif group_key == 'A':\r
- weekday = locale_time.f_weekday.index(found_dict['A'].lower())\r
- elif group_key == 'a':\r
- weekday = locale_time.a_weekday.index(found_dict['a'].lower())\r
- elif group_key == 'w':\r
- weekday = int(found_dict['w'])\r
- if weekday == 0:\r
- weekday = 6\r
- else:\r
- weekday -= 1\r
- elif group_key == 'j':\r
- julian = int(found_dict['j'])\r
- elif group_key in ('U', 'W'):\r
- week_of_year = int(found_dict[group_key])\r
- if group_key == 'U':\r
- # U starts week on Sunday.\r
- week_of_year_start = 6\r
- else:\r
- # W starts week on Monday.\r
- week_of_year_start = 0\r
- elif group_key == 'Z':\r
- # Since -1 is default value only need to worry about setting tz if\r
- # it can be something other than -1.\r
- found_zone = found_dict['Z'].lower()\r
- for value, tz_values in enumerate(locale_time.timezone):\r
- if found_zone in tz_values:\r
- # Deal with bad locale setup where timezone names are the\r
- # same and yet time.daylight is true; too ambiguous to\r
- # be able to tell what timezone has daylight savings\r
- if (time.tzname[0] == time.tzname[1] and\r
- time.daylight and found_zone not in ("utc", "gmt")):\r
- break\r
- else:\r
- tz = value\r
- break\r
- # If we know the week of the year and what day of that week, we can figure\r
- # out the Julian day of the year.\r
- if julian == -1 and week_of_year != -1 and weekday != -1:\r
- week_starts_Mon = True if week_of_year_start == 0 else False\r
- julian = _calc_julian_from_U_or_W(year, week_of_year, weekday,\r
- week_starts_Mon)\r
- # Cannot pre-calculate datetime_date() since can change in Julian\r
- # calculation and thus could have different value for the day of the week\r
- # calculation.\r
- if julian == -1:\r
- # Need to add 1 to result since first day of the year is 1, not 0.\r
- julian = datetime_date(year, month, day).toordinal() - \\r
- datetime_date(year, 1, 1).toordinal() + 1\r
- else: # Assume that if they bothered to include Julian day it will\r
- # be accurate.\r
- datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal())\r
- year = datetime_result.year\r
- month = datetime_result.month\r
- day = datetime_result.day\r
- if weekday == -1:\r
- weekday = datetime_date(year, month, day).weekday()\r
- return (time.struct_time((year, month, day,\r
- hour, minute, second,\r
- weekday, julian, tz)), fraction)\r
-\r
-def _strptime_time(data_string, format="%a %b %d %H:%M:%S %Y"):\r
- return _strptime(data_string, format)[0]\r