Back to index

python3.2  3.2.2
Classes | Functions | Variables
_strptime Namespace Reference

Classes

class  LocaleTime
class  TimeRE

Functions

def _getlang
def _calc_julian_from_U_or_W
def _strptime
def _strptime_time
def _strptime_datetime

Variables

list __all__ = []
tuple _cache_lock = _thread_allocate_lock()
tuple _TimeRE_cache = TimeRE()
int _CACHE_MAX_SIZE = 5
dictionary _regex_cache = {}

Detailed Description

Strptime-related classes and functions.

CLASSES:
    LocaleTime -- Discovers and stores locale-specific time information
    TimeRE -- Creates regexes for pattern matching a string of text containing
        time information

FUNCTIONS:
    _getlang -- Figure out what language is being used for the locale
    strptime -- Calculates the time struct represented by the passed-in string

Function Documentation

def _strptime._calc_julian_from_U_or_W (   year,
  week_of_year,
  day_of_week,
  week_starts_Mon 
) [private]
Calculate the Julian day based on the year, week of the year, and day of
the week, with week_start_day representing whether the week of the year
assumes the week starts on Sunday or Monday (6 or 0).

Definition at line 277 of file _strptime.py.

00277 
00278 def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon):
00279     """Calculate the Julian day based on the year, week of the year, and day of
00280     the week, with week_start_day representing whether the week of the year
00281     assumes the week starts on Sunday or Monday (6 or 0)."""
00282     first_weekday = datetime_date(year, 1, 1).weekday()
00283     # If we are dealing with the %U directive (week starts on Sunday), it's
00284     # easier to just shift the view to Sunday being the first day of the
00285     # week.
00286     if not week_starts_Mon:
00287         first_weekday = (first_weekday + 1) % 7
00288         day_of_week = (day_of_week + 1) % 7
00289     # Need to watch out for a week 0 (when the first day of the year is not
00290     # the same as that specified by %U or %W).
00291     week_0_length = (7 - first_weekday) % 7
00292     if week_of_year == 0:
00293         return 1 + day_of_week - first_weekday
00294     else:
00295         days_to_week = week_0_length + (7 * (week_of_year - 1))
00296         return 1 + days_to_week + day_of_week
00297 

Here is the call graph for this function:

Here is the caller graph for this function:

def _strptime._getlang ( ) [private]

Definition at line 29 of file _strptime.py.

00029 
00030 def _getlang():
00031     # Figure out what the current language is set to.
00032     return locale.getlocale(locale.LC_TIME)

Here is the call graph for this function:

Here is the caller graph for this function:

def _strptime._strptime (   data_string,
  format = "%a %b %d %H:%M:%S %Y" 
) [private]
Return a 2-tuple consisting of a time struct and an int containing
the number of microseconds based on the input string and the
format string.

Definition at line 298 of file _strptime.py.

00298 
00299 def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
00300     """Return a 2-tuple consisting of a time struct and an int containing
00301     the number of microseconds based on the input string and the
00302     format string."""
00303 
00304     for index, arg in enumerate([data_string, format]):
00305         if not isinstance(arg, str):
00306             msg = "strptime() argument {} must be str, not {}"
00307             raise TypeError(msg.format(index, type(arg)))
00308 
00309     global _TimeRE_cache, _regex_cache
00310     with _cache_lock:
00311 
00312         if _getlang() != _TimeRE_cache.locale_time.lang:
00313             _TimeRE_cache = TimeRE()
00314             _regex_cache.clear()
00315         if len(_regex_cache) > _CACHE_MAX_SIZE:
00316             _regex_cache.clear()
00317         locale_time = _TimeRE_cache.locale_time
00318         format_regex = _regex_cache.get(format)
00319         if not format_regex:
00320             try:
00321                 format_regex = _TimeRE_cache.compile(format)
00322             # KeyError raised when a bad format is found; can be specified as
00323             # \\, in which case it was a stray % but with a space after it
00324             except KeyError as err:
00325                 bad_directive = err.args[0]
00326                 if bad_directive == "\\":
00327                     bad_directive = "%"
00328                 del err
00329                 raise ValueError("'%s' is a bad directive in format '%s'" %
00330                                     (bad_directive, format))
00331             # IndexError only occurs when the format string is "%"
00332             except IndexError:
00333                 raise ValueError("stray %% in format '%s'" % format)
00334             _regex_cache[format] = format_regex
00335     found = format_regex.match(data_string)
00336     if not found:
00337         raise ValueError("time data %r does not match format %r" %
00338                          (data_string, format))
00339     if len(data_string) != found.end():
00340         raise ValueError("unconverted data remains: %s" %
00341                           data_string[found.end():])
00342 
00343     year = 1900
00344     month = day = 1
00345     hour = minute = second = fraction = 0
00346     tz = -1
00347     tzoffset = None
00348     # Default to -1 to signify that values not known; not critical to have,
00349     # though
00350     week_of_year = -1
00351     week_of_year_start = -1
00352     # weekday and julian defaulted to -1 so as to signal need to calculate
00353     # values
00354     weekday = julian = -1
00355     found_dict = found.groupdict()
00356     for group_key in found_dict.keys():
00357         # Directives not explicitly handled below:
00358         #   c, x, X
00359         #      handled by making out of other directives
00360         #   U, W
00361         #      worthless without day of the week
00362         if group_key == 'y':
00363             year = int(found_dict['y'])
00364             # Open Group specification for strptime() states that a %y
00365             #value in the range of [00, 68] is in the century 2000, while
00366             #[69,99] is in the century 1900
00367             if year <= 68:
00368                 year += 2000
00369             else:
00370                 year += 1900
00371         elif group_key == 'Y':
00372             year = int(found_dict['Y'])
00373         elif group_key == 'm':
00374             month = int(found_dict['m'])
00375         elif group_key == 'B':
00376             month = locale_time.f_month.index(found_dict['B'].lower())
00377         elif group_key == 'b':
00378             month = locale_time.a_month.index(found_dict['b'].lower())
00379         elif group_key == 'd':
00380             day = int(found_dict['d'])
00381         elif group_key == 'H':
00382             hour = int(found_dict['H'])
00383         elif group_key == 'I':
00384             hour = int(found_dict['I'])
00385             ampm = found_dict.get('p', '').lower()
00386             # If there was no AM/PM indicator, we'll treat this like AM
00387             if ampm in ('', locale_time.am_pm[0]):
00388                 # We're in AM so the hour is correct unless we're
00389                 # looking at 12 midnight.
00390                 # 12 midnight == 12 AM == hour 0
00391                 if hour == 12:
00392                     hour = 0
00393             elif ampm == locale_time.am_pm[1]:
00394                 # We're in PM so we need to add 12 to the hour unless
00395                 # we're looking at 12 noon.
00396                 # 12 noon == 12 PM == hour 12
00397                 if hour != 12:
00398                     hour += 12
00399         elif group_key == 'M':
00400             minute = int(found_dict['M'])
00401         elif group_key == 'S':
00402             second = int(found_dict['S'])
00403         elif group_key == 'f':
00404             s = found_dict['f']
00405             # Pad to always return microseconds.
00406             s += "0" * (6 - len(s))
00407             fraction = int(s)
00408         elif group_key == 'A':
00409             weekday = locale_time.f_weekday.index(found_dict['A'].lower())
00410         elif group_key == 'a':
00411             weekday = locale_time.a_weekday.index(found_dict['a'].lower())
00412         elif group_key == 'w':
00413             weekday = int(found_dict['w'])
00414             if weekday == 0:
00415                 weekday = 6
00416             else:
00417                 weekday -= 1
00418         elif group_key == 'j':
00419             julian = int(found_dict['j'])
00420         elif group_key in ('U', 'W'):
00421             week_of_year = int(found_dict[group_key])
00422             if group_key == 'U':
00423                 # U starts week on Sunday.
00424                 week_of_year_start = 6
00425             else:
00426                 # W starts week on Monday.
00427                 week_of_year_start = 0
00428         elif group_key == 'z':
00429             z = found_dict['z']
00430             tzoffset = int(z[1:3]) * 60 + int(z[3:5])
00431             if z.startswith("-"):
00432                 tzoffset = -tzoffset
00433         elif group_key == 'Z':
00434             # Since -1 is default value only need to worry about setting tz if
00435             # it can be something other than -1.
00436             found_zone = found_dict['Z'].lower()
00437             for value, tz_values in enumerate(locale_time.timezone):
00438                 if found_zone in tz_values:
00439                     # Deal with bad locale setup where timezone names are the
00440                     # same and yet time.daylight is true; too ambiguous to
00441                     # be able to tell what timezone has daylight savings
00442                     if (time.tzname[0] == time.tzname[1] and
00443                        time.daylight and found_zone not in ("utc", "gmt")):
00444                         break
00445                     else:
00446                         tz = value
00447                         break
00448     # If we know the week of the year and what day of that week, we can figure
00449     # out the Julian day of the year.
00450     if julian == -1 and week_of_year != -1 and weekday != -1:
00451         week_starts_Mon = True if week_of_year_start == 0 else False
00452         julian = _calc_julian_from_U_or_W(year, week_of_year, weekday,
00453                                             week_starts_Mon)
00454     # Cannot pre-calculate datetime_date() since can change in Julian
00455     # calculation and thus could have different value for the day of the week
00456     # calculation.
00457     if julian == -1:
00458         # Need to add 1 to result since first day of the year is 1, not 0.
00459         julian = datetime_date(year, month, day).toordinal() - \
00460                   datetime_date(year, 1, 1).toordinal() + 1
00461     else:  # Assume that if they bothered to include Julian day it will
00462            # be accurate.
00463         datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal())
00464         year = datetime_result.year
00465         month = datetime_result.month
00466         day = datetime_result.day
00467     if weekday == -1:
00468         weekday = datetime_date(year, month, day).weekday()
00469     # Add timezone info
00470     tzname = found_dict.get("Z")
00471     if tzoffset is not None:
00472         gmtoff = tzoffset * 60
00473     else:
00474         gmtoff = None
00475 
00476     return (year, month, day,
00477             hour, minute, second,
00478             weekday, julian, tz, gmtoff, tzname), fraction

Here is the call graph for this function:

Here is the caller graph for this function:

def _strptime._strptime_datetime (   cls,
  data_string,
  format = "%a %b %d %H:%M:%S %Y" 
) [private]
Return a class cls instance based on the input string and the
format string.

Definition at line 485 of file _strptime.py.

00485 
00486 def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"):
00487     """Return a class cls instance based on the input string and the
00488     format string."""
00489     tt, fraction = _strptime(data_string, format)
00490     gmtoff, tzname = tt[-2:]
00491     args = tt[:6] + (fraction,)
00492     if gmtoff is not None:
00493         tzdelta = datetime_timedelta(seconds=gmtoff)
00494         if tzname:
00495             tz = datetime_timezone(tzdelta, tzname)
00496         else:
00497             tz = datetime_timezone(tzdelta)
00498         args += (tz,)
00499 
00500     return cls(*args)

Here is the caller graph for this function:

def _strptime._strptime_time (   data_string,
  format = "%a %b %d %H:%M:%S %Y" 
) [private]
Return a time struct based on the input string and the
format string.

Definition at line 479 of file _strptime.py.

00479 
00480 def _strptime_time(data_string, format="%a %b %d %H:%M:%S %Y"):
00481     """Return a time struct based on the input string and the
00482     format string."""
00483     tt = _strptime(data_string, format)[0]
00484     return time.struct_time(tt[:9])

Here is the caller graph for this function:


Variable Documentation

list _strptime.__all__ = []

Definition at line 27 of file _strptime.py.

tuple _strptime._cache_lock = _thread_allocate_lock()

Definition at line 270 of file _strptime.py.

Definition at line 274 of file _strptime.py.

Definition at line 275 of file _strptime.py.

Definition at line 273 of file _strptime.py.