Back to index

moin  1.9.0~rc2
Public Member Functions | Public Attributes | Private Member Functions
MoinMoin.support.parsedatetime.parsedatetime.Calendar Class Reference

List of all members.

Public Member Functions

def __init__
def parseDate
def parseDateText
def evalRanges
def parse
def inc

Public Attributes

 ptc
 weekdyFlag
 dateStdFlag
 dateStrFlag
 timeStdFlag
 meridianFlag
 dayStrFlag
 timeStrFlag
 modifierFlag
 modifier2Flag
 unitsFlag
 qunitsFlag
 timeFlag
 dateFlag

Private Member Functions

def _convertUnitAsWords
def _buildTime
def _CalculateDOWDelta
def _evalModifier
def _evalModifier2
def _evalString

Detailed Description

A collection of routines to input, parse and manipulate date and times.
The text can either be 'normal' date values or it can be human readable.

Definition at line 179 of file parsedatetime.py.


Constructor & Destructor Documentation

Default constructor for the L{Calendar} class.

@type  constants: object
@param constants: Instance of the class L{parsedatetime_consts.Constants}

@rtype:  object
@return: L{Calendar} instance

Definition at line 185 of file parsedatetime.py.

00185 
00186     def __init__(self, constants=None):
00187         """
00188         Default constructor for the L{Calendar} class.
00189 
00190         @type  constants: object
00191         @param constants: Instance of the class L{parsedatetime_consts.Constants}
00192 
00193         @rtype:  object
00194         @return: L{Calendar} instance
00195         """
00196           # if a constants reference is not included, use default
00197         if constants is None:
00198             self.ptc = parsedatetime_consts.Constants()
00199         else:
00200             self.ptc = constants
00201 
00202         self.weekdyFlag    = False  # monday/tuesday/...
00203         self.dateStdFlag   = False  # 07/21/06
00204         self.dateStrFlag   = False  # July 21st, 2006
00205         self.timeStdFlag   = False  # 5:50 
00206         self.meridianFlag  = False  # am/pm
00207         self.dayStrFlag    = False  # tomorrow/yesterday/today/..
00208         self.timeStrFlag   = False  # lunch/noon/breakfast/...
00209         self.modifierFlag  = False  # after/before/prev/next/..
00210         self.modifier2Flag = False  # after/before/prev/next/..
00211         self.unitsFlag     = False  # hrs/weeks/yrs/min/..
00212         self.qunitsFlag    = False  # h/m/t/d..
00213 
00214         self.timeFlag      = 0
00215         self.dateFlag      = 0
00216 


Member Function Documentation

def MoinMoin.support.parsedatetime.parsedatetime.Calendar._buildTime (   self,
  source,
  quantity,
  modifier,
  units 
) [private]
Take C{quantity}, C{modifier} and C{unit} strings and convert them into values.
After converting, calcuate the time and return the adjusted sourceTime.

@type  source:   time
@param source:   time to use as the base (or source)
@type  quantity: string
@param quantity: quantity string
@type  modifier: string
@param modifier: how quantity and units modify the source time
@type  units:    string
@param units:    unit of the quantity (i.e. hours, days, months, etc)

@rtype:  struct_time
@return: C{struct_time} of the calculated time

Definition at line 237 of file parsedatetime.py.

00237 
00238     def _buildTime(self, source, quantity, modifier, units):
00239         """
00240         Take C{quantity}, C{modifier} and C{unit} strings and convert them into values.
00241         After converting, calcuate the time and return the adjusted sourceTime.
00242 
00243         @type  source:   time
00244         @param source:   time to use as the base (or source)
00245         @type  quantity: string
00246         @param quantity: quantity string
00247         @type  modifier: string
00248         @param modifier: how quantity and units modify the source time
00249         @type  units:    string
00250         @param units:    unit of the quantity (i.e. hours, days, months, etc)
00251 
00252         @rtype:  struct_time
00253         @return: C{struct_time} of the calculated time
00254         """
00255         if _debug:
00256             print '_buildTime: [%s][%s][%s]' % (quantity, modifier, units)
00257 
00258         if source is None:
00259             source = time.localtime()
00260 
00261         if quantity is None:
00262             quantity = ''
00263         else:
00264             quantity = quantity.strip()
00265 
00266         if len(quantity) == 0:
00267             qty = 1
00268         else:
00269             try:
00270                 qty = int(quantity)
00271             except ValueError:
00272                 qty = 0
00273 
00274         if modifier in self.ptc.Modifiers:
00275             qty = qty * self.ptc.Modifiers[modifier]
00276 
00277             if units is None or units == '':
00278                 units = 'dy'
00279 
00280         # plurals are handled by regex's (could be a bug tho)
00281 
00282         (yr, mth, dy, hr, mn, sec, _, _, _) = source
00283 
00284         start  = datetime.datetime(yr, mth, dy, hr, mn, sec)
00285         target = start
00286 
00287         if units.startswith('y'):
00288             target        = self.inc(start, year=qty)
00289             self.dateFlag = 1
00290         elif units.endswith('th') or units.endswith('ths'):
00291             target        = self.inc(start, month=qty)
00292             self.dateFlag = 1
00293         else:
00294             if units.startswith('d'):
00295                 target        = start + datetime.timedelta(days=qty)
00296                 self.dateFlag = 1
00297             elif units.startswith('h'):
00298                 target        = start + datetime.timedelta(hours=qty)
00299                 self.timeFlag = 2
00300             elif units.startswith('m'):
00301                 target        = start + datetime.timedelta(minutes=qty)
00302                 self.timeFlag = 2
00303             elif units.startswith('s'):
00304                 target        = start + datetime.timedelta(seconds=qty)
00305                 self.timeFlag = 2
00306             elif units.startswith('w'):
00307                 target        = start + datetime.timedelta(weeks=qty)
00308                 self.dateFlag = 1
00309 
00310         return target.timetuple()
00311 

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.parsedatetime.parsedatetime.Calendar._CalculateDOWDelta (   self,
  wd,
  wkdy,
  offset,
  style,
  currentDayStyle 
) [private]
Based on the C{style} and C{currentDayStyle} determine what
day-of-week value is to be returned.

@type  wd:              integer
@param wd:              day-of-week value for the current day
@type  wkdy:            integer
@param wkdy:            day-of-week value for the parsed day
@type  offset:          integer
@param offset:          offset direction for any modifiers (-1, 0, 1)
@type  style:           integer
@param style:           normally the value set in C{Constants.DOWParseStyle}
@type  currentDayStyle: integer
@param currentDayStyle: normally the value set in C{Constants.CurrentDOWParseStyle}

@rtype:  integer
@return: calculated day-of-week

Definition at line 609 of file parsedatetime.py.

00609 
00610     def _CalculateDOWDelta(self, wd, wkdy, offset, style, currentDayStyle):
00611         """
00612         Based on the C{style} and C{currentDayStyle} determine what
00613         day-of-week value is to be returned.
00614 
00615         @type  wd:              integer
00616         @param wd:              day-of-week value for the current day
00617         @type  wkdy:            integer
00618         @param wkdy:            day-of-week value for the parsed day
00619         @type  offset:          integer
00620         @param offset:          offset direction for any modifiers (-1, 0, 1)
00621         @type  style:           integer
00622         @param style:           normally the value set in C{Constants.DOWParseStyle}
00623         @type  currentDayStyle: integer
00624         @param currentDayStyle: normally the value set in C{Constants.CurrentDOWParseStyle}
00625 
00626         @rtype:  integer
00627         @return: calculated day-of-week
00628         """
00629         if offset == 1:
00630             # modifier is indicating future week eg: "next".
00631             # DOW is calculated as DOW of next week
00632             diff = 7 - wd + wkdy
00633 
00634         elif offset == -1:
00635             # modifier is indicating past week eg: "last","previous"
00636             # DOW is calculated as DOW of previous week
00637             diff = wkdy - wd - 7
00638 
00639         elif offset == 0:
00640             # modifier is indiacting current week eg: "this"
00641             # DOW is calculated as DOW of this week
00642             diff = wkdy - wd
00643 
00644         elif offset == 2:
00645             # no modifier is present.
00646             # i.e. string to be parsed is just DOW
00647             if style == 1:
00648                 # next occurance of the DOW is calculated
00649                 if currentDayStyle == True:
00650                     if wkdy >= wd:
00651                         diff = wkdy - wd
00652                     else:
00653                         diff = 7 - wd + wkdy
00654                 else:
00655                     if wkdy > wd:
00656                         diff = wkdy - wd
00657                     else:
00658                         diff = 7 - wd + wkdy
00659 
00660             elif style == -1:
00661                 # last occurance of the DOW is calculated
00662                 if currentDayStyle == True:
00663                     if wkdy <= wd:
00664                         diff = wkdy - wd
00665                     else:
00666                         diff = wkdy - wd - 7
00667                 else:
00668                     if wkdy < wd:
00669                         diff = wkdy - wd
00670                     else:
00671                         diff = wkdy - wd - 7
00672             else:
00673                 # occurance of the DOW in the current week is calculated
00674                 diff = wkdy - wd
00675 
00676         if _debug:
00677             print "wd %s, wkdy %s, offset %d, style %d\n" % (wd, wkdy, offset, style)
00678 
00679         return diff
00680 

Here is the caller graph for this function:

Converts text units into their number value

Five = 5
Twenty Five = 25
Two hundred twenty five = 225
Two thousand and twenty five = 2025
Two thousand twenty five = 2025

@type  unitText: string
@param unitText: number text to convert

@rtype:  integer
@return: numerical value of unitText

Definition at line 217 of file parsedatetime.py.

00217 
00218     def _convertUnitAsWords(self, unitText):
00219         """
00220         Converts text units into their number value
00221 
00222         Five = 5
00223         Twenty Five = 25
00224         Two hundred twenty five = 225
00225         Two thousand and twenty five = 2025
00226         Two thousand twenty five = 2025
00227 
00228         @type  unitText: string
00229         @param unitText: number text to convert
00230 
00231         @rtype:  integer
00232         @return: numerical value of unitText
00233         """
00234         # TODO: implement this
00235         pass
00236 

def MoinMoin.support.parsedatetime.parsedatetime.Calendar._evalModifier (   self,
  modifier,
  chunk1,
  chunk2,
  sourceTime 
) [private]
Evaluate the C{modifier} string and following text (passed in
as C{chunk1} and C{chunk2}) and if they match any known modifiers
calculate the delta and apply it to C{sourceTime}.

@type  modifier:   string
@param modifier:   modifier text to apply to sourceTime
@type  chunk1:     string
@param chunk1:     first text chunk that followed modifier (if any)
@type  chunk2:     string
@param chunk2:     second text chunk that followed modifier (if any)
@type  sourceTime: struct_time
@param sourceTime: C{struct_time} value to use as the base

@rtype:  tuple
@return: tuple of: remaining text and the modified sourceTime

Definition at line 681 of file parsedatetime.py.

00681 
00682     def _evalModifier(self, modifier, chunk1, chunk2, sourceTime):
00683         """
00684         Evaluate the C{modifier} string and following text (passed in
00685         as C{chunk1} and C{chunk2}) and if they match any known modifiers
00686         calculate the delta and apply it to C{sourceTime}.
00687 
00688         @type  modifier:   string
00689         @param modifier:   modifier text to apply to sourceTime
00690         @type  chunk1:     string
00691         @param chunk1:     first text chunk that followed modifier (if any)
00692         @type  chunk2:     string
00693         @param chunk2:     second text chunk that followed modifier (if any)
00694         @type  sourceTime: struct_time
00695         @param sourceTime: C{struct_time} value to use as the base
00696 
00697         @rtype:  tuple
00698         @return: tuple of: remaining text and the modified sourceTime
00699         """
00700         offset = self.ptc.Modifiers[modifier]
00701 
00702         if sourceTime is not None:
00703             (yr, mth, dy, hr, mn, sec, wd, yd, isdst) = sourceTime
00704         else:
00705             (yr, mth, dy, hr, mn, sec, wd, yd, isdst) = time.localtime()
00706 
00707         # capture the units after the modifier and the remaining
00708         # string after the unit
00709         m = self.ptc.CRE_REMAINING.search(chunk2)
00710         if m is not None:
00711             index  = m.start() + 1
00712             unit   = chunk2[:m.start()]
00713             chunk2 = chunk2[index:]
00714         else:
00715             unit   = chunk2
00716             chunk2 = ''
00717 
00718         flag = False
00719 
00720         if unit == 'month' or \
00721            unit == 'mth' or \
00722            unit == 'm':
00723             if offset == 0:
00724                 dy         = self.ptc.daysInMonth(mth, yr)
00725                 sourceTime = (yr, mth, dy, 9, 0, 0, wd, yd, isdst)
00726             elif offset == 2:
00727                 # if day is the last day of the month, calculate the last day
00728                 # of the next month
00729                 if dy == self.ptc.daysInMonth(mth, yr):
00730                     dy = self.ptc.daysInMonth(mth + 1, yr)
00731 
00732                 start      = datetime.datetime(yr, mth, dy, 9, 0, 0)
00733                 target     = self.inc(start, month=1)
00734                 sourceTime = target.timetuple()
00735             else:
00736                 start      = datetime.datetime(yr, mth, 1, 9, 0, 0)
00737                 target     = self.inc(start, month=offset)
00738                 sourceTime = target.timetuple()
00739 
00740             flag = True
00741             self.dateFlag = 1
00742 
00743         if unit == 'week' or \
00744              unit == 'wk' or \
00745              unit == 'w':
00746             if offset == 0:
00747                 start      = datetime.datetime(yr, mth, dy, 17, 0, 0)
00748                 target     = start + datetime.timedelta(days=(4 - wd))
00749                 sourceTime = target.timetuple()
00750             elif offset == 2:
00751                 start      = datetime.datetime(yr, mth, dy, 9, 0, 0)
00752                 target     = start + datetime.timedelta(days=7)
00753                 sourceTime = target.timetuple()
00754             else:
00755                 return self._evalModifier(modifier, chunk1, "monday " + chunk2, sourceTime)
00756 
00757             flag          = True
00758             self.dateFlag = 1
00759 
00760         if unit == 'day' or \
00761             unit == 'dy' or \
00762             unit == 'd':
00763             if offset == 0:
00764                 sourceTime    = (yr, mth, dy, 17, 0, 0, wd, yd, isdst)
00765                 self.timeFlag = 2
00766             elif offset == 2:
00767                 start      = datetime.datetime(yr, mth, dy, hr, mn, sec)
00768                 target     = start + datetime.timedelta(days=1)
00769                 sourceTime = target.timetuple()
00770             else:
00771                 start      = datetime.datetime(yr, mth, dy, 9, 0, 0)
00772                 target     = start + datetime.timedelta(days=offset)
00773                 sourceTime = target.timetuple()
00774 
00775             flag          = True
00776             self.dateFlag = 1
00777 
00778         if unit == 'hour' or \
00779            unit == 'hr':
00780             if offset == 0:
00781                 sourceTime = (yr, mth, dy, hr, 0, 0, wd, yd, isdst)
00782             else:
00783                 start      = datetime.datetime(yr, mth, dy, hr, 0, 0)
00784                 target     = start + datetime.timedelta(hours=offset)
00785                 sourceTime = target.timetuple()
00786 
00787             flag          = True
00788             self.timeFlag = 2
00789 
00790         if unit == 'year' or \
00791              unit == 'yr' or \
00792              unit == 'y':
00793             if offset == 0:
00794                 sourceTime = (yr, 12, 31, hr, mn, sec, wd, yd, isdst)
00795             elif offset == 2:
00796                 sourceTime = (yr + 1, mth, dy, hr, mn, sec, wd, yd, isdst)
00797             else:
00798                 sourceTime = (yr + offset, 1, 1, 9, 0, 0, wd, yd, isdst)
00799 
00800             flag          = True
00801             self.dateFlag = 1
00802 
00803         if flag == False:
00804             m = self.ptc.CRE_WEEKDAY.match(unit)
00805             if m is not None:
00806                 wkdy          = m.group()
00807                 self.dateFlag = 1
00808 
00809                 if modifier == 'eod':
00810                     # Calculate the  upcoming weekday
00811                     self.modifierFlag = False
00812                     (sourceTime, _)   = self.parse(wkdy, sourceTime)
00813                     sources           = self.ptc.buildSources(sourceTime)
00814                     self.timeFlag     = 2
00815 
00816                     if modifier in sources:
00817                         sourceTime = sources[modifier]
00818 
00819                 else:
00820                     wkdy       = self.ptc.WeekdayOffsets[wkdy]
00821                     diff       = self._CalculateDOWDelta(wd, wkdy, offset,
00822                                                          self.ptc.DOWParseStyle,
00823                                                          self.ptc.CurrentDOWParseStyle)
00824                     start      = datetime.datetime(yr, mth, dy, 9, 0, 0)
00825                     target     = start + datetime.timedelta(days=diff)
00826                     sourceTime = target.timetuple()
00827 
00828                 flag          = True
00829                 self.dateFlag = 1
00830 
00831         if not flag:
00832             m = self.ptc.CRE_TIME.match(unit)
00833             if m is not None:
00834                 self.modifierFlag = False
00835                 (yr, mth, dy, hr, mn, sec, wd, yd, isdst), _ = self.parse(unit)
00836 
00837                 start      = datetime.datetime(yr, mth, dy, hr, mn, sec)
00838                 target     = start + datetime.timedelta(days=offset)
00839                 sourceTime = target.timetuple()
00840                 flag       = True
00841             else:
00842                 self.modifierFlag = False
00843 
00844                 # check if the remaining text is parsable and if so,
00845                 # use it as the base time for the modifier source time
00846                 t, flag2 = self.parse('%s %s' % (chunk1, unit), sourceTime)
00847 
00848                 if flag2 != 0:
00849                     sourceTime = t
00850 
00851                 sources = self.ptc.buildSources(sourceTime)
00852 
00853                 if modifier in sources:
00854                     sourceTime    = sources[modifier]
00855                     flag          = True
00856                     self.timeFlag = 2
00857 
00858         # if the word after next is a number, the string is more than likely
00859         # to be "next 4 hrs" which we will have to combine the units with the
00860         # rest of the string
00861         if not flag:
00862             if offset < 0:
00863                 # if offset is negative, the unit has to be made negative
00864                 unit = '-%s' % unit
00865 
00866             chunk2 = '%s %s' % (unit, chunk2)
00867 
00868         self.modifierFlag = False
00869 
00870         #return '%s %s' % (chunk1, chunk2), sourceTime
00871         return '%s' % chunk2, sourceTime

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.parsedatetime.parsedatetime.Calendar._evalModifier2 (   self,
  modifier,
  chunk1,
  chunk2,
  sourceTime 
) [private]
Evaluate the C{modifier} string and following text (passed in
as C{chunk1} and C{chunk2}) and if they match any known modifiers
calculate the delta and apply it to C{sourceTime}.

@type  modifier:   string
@param modifier:   modifier text to apply to C{sourceTime}
@type  chunk1:     string
@param chunk1:     first text chunk that followed modifier (if any)
@type  chunk2:     string
@param chunk2:     second text chunk that followed modifier (if any)
@type  sourceTime: struct_time
@param sourceTime: C{struct_time} value to use as the base

@rtype:  tuple
@return: tuple of: remaining text and the modified sourceTime

Definition at line 872 of file parsedatetime.py.

00872 
00873     def _evalModifier2(self, modifier, chunk1 , chunk2, sourceTime):
00874         """
00875         Evaluate the C{modifier} string and following text (passed in
00876         as C{chunk1} and C{chunk2}) and if they match any known modifiers
00877         calculate the delta and apply it to C{sourceTime}.
00878 
00879         @type  modifier:   string
00880         @param modifier:   modifier text to apply to C{sourceTime}
00881         @type  chunk1:     string
00882         @param chunk1:     first text chunk that followed modifier (if any)
00883         @type  chunk2:     string
00884         @param chunk2:     second text chunk that followed modifier (if any)
00885         @type  sourceTime: struct_time
00886         @param sourceTime: C{struct_time} value to use as the base
00887 
00888         @rtype:  tuple
00889         @return: tuple of: remaining text and the modified sourceTime
00890         """
00891         offset = self.ptc.Modifiers[modifier]
00892         digit  = r'\d+'
00893 
00894         self.modifier2Flag = False
00895 
00896         # If the string after the negative modifier starts with digits,
00897         # then it is likely that the string is similar to ' before 3 days'
00898         # or 'evening prior to 3 days'.
00899         # In this case, the total time is calculated by subtracting '3 days'
00900         # from the current date.
00901         # So, we have to identify the quantity and negate it before parsing
00902         # the string.
00903         # This is not required for strings not starting with digits since the
00904         # string is enough to calculate the sourceTime
00905         if chunk2 != '':
00906             if offset < 0:
00907                 m = re.match(digit, chunk2.strip())
00908                 if m is not None:
00909                     qty    = int(m.group()) * -1
00910                     chunk2 = chunk2[m.end():]
00911                     chunk2 = '%d%s' % (qty, chunk2)
00912 
00913             sourceTime, flag1 = self.parse(chunk2, sourceTime)
00914             if flag1 == 0:
00915                 flag1 = True
00916             else:
00917                 flag1 = False
00918             flag2 = False
00919         else:
00920             flag1 = False
00921 
00922         if chunk1 != '':
00923             if offset < 0:
00924                 m = re.search(digit, chunk1.strip())
00925                 if m is not None:
00926                     qty    = int(m.group()) * -1
00927                     chunk1 = chunk1[m.end():]
00928                     chunk1 = '%d%s' % (qty, chunk1)
00929 
00930             tempDateFlag       = self.dateFlag
00931             tempTimeFlag       = self.timeFlag
00932             sourceTime2, flag2 = self.parse(chunk1, sourceTime)
00933         else:
00934             return sourceTime, (flag1 and flag2)
00935 
00936         # if chunk1 is not a datetime and chunk2 is then do not use datetime
00937         # value returned by parsing chunk1
00938         if not (flag1 == False and flag2 == 0):
00939             sourceTime = sourceTime2
00940         else:
00941             self.timeFlag = tempTimeFlag
00942             self.dateFlag = tempDateFlag
00943 
00944         return sourceTime, (flag1 and flag2)
00945 

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.parsedatetime.parsedatetime.Calendar._evalString (   self,
  datetimeString,
  sourceTime = None 
) [private]
Calculate the datetime based on flags set by the L{parse()} routine

Examples handled::
    RFC822, W3CDTF formatted dates
    HH:MM[:SS][ am/pm]
    MM/DD/YYYY
    DD MMMM YYYY

@type  datetimeString: string
@param datetimeString: text to try and parse as more "traditional"
               date/time text
@type  sourceTime:     struct_time
@param sourceTime:     C{struct_time} value to use as the base

@rtype:  datetime
@return: calculated C{struct_time} value or current C{struct_time}
 if not parsed

Definition at line 946 of file parsedatetime.py.

00946 
00947     def _evalString(self, datetimeString, sourceTime=None):
00948         """
00949         Calculate the datetime based on flags set by the L{parse()} routine
00950 
00951         Examples handled::
00952             RFC822, W3CDTF formatted dates
00953             HH:MM[:SS][ am/pm]
00954             MM/DD/YYYY
00955             DD MMMM YYYY
00956 
00957         @type  datetimeString: string
00958         @param datetimeString: text to try and parse as more "traditional"
00959                                date/time text
00960         @type  sourceTime:     struct_time
00961         @param sourceTime:     C{struct_time} value to use as the base
00962 
00963         @rtype:  datetime
00964         @return: calculated C{struct_time} value or current C{struct_time}
00965                  if not parsed
00966         """
00967         s   = datetimeString.strip()
00968         now = time.localtime()
00969 
00970         # Given string date is a RFC822 date
00971         if sourceTime is None:
00972             sourceTime = _parse_date_rfc822(s)
00973 
00974             if sourceTime is not None:
00975                 (yr, mth, dy, hr, mn, sec, wd, yd, isdst, _) = sourceTime
00976                 self.dateFlag = 1
00977 
00978                 if (hr != 0) and (mn != 0) and (sec != 0):
00979                     self.timeFlag = 2
00980 
00981                 sourceTime = (yr, mth, dy, hr, mn, sec, wd, yd, isdst)
00982 
00983         # Given string date is a W3CDTF date
00984         if sourceTime is None:
00985             sourceTime = _parse_date_w3dtf(s)
00986 
00987             if sourceTime is not None:
00988                 self.dateFlag = 1
00989                 self.timeFlag = 2
00990 
00991         if sourceTime is None:
00992             s = s.lower()
00993 
00994         # Given string is in the format HH:MM(:SS)(am/pm)
00995         if self.meridianFlag:
00996             if sourceTime is None:
00997                 (yr, mth, dy, hr, mn, sec, wd, yd, isdst) = now
00998             else:
00999                 (yr, mth, dy, hr, mn, sec, wd, yd, isdst) = sourceTime
01000 
01001             m = self.ptc.CRE_TIMEHMS2.search(s)
01002             if m is not None:
01003                 dt = s[:m.start('meridian')].strip()
01004                 if len(dt) <= 2:
01005                     hr  = int(dt)
01006                     mn  = 0
01007                     sec = 0
01008                 else:
01009                     hr, mn, sec = _extract_time(m)
01010 
01011                 if hr == 24:
01012                     hr = 0
01013 
01014                 sourceTime = (yr, mth, dy, hr, mn, sec, wd, yd, isdst)
01015                 meridian   = m.group('meridian').lower()
01016 
01017                   # if 'am' found and hour is 12 - force hour to 0 (midnight)
01018                 if (meridian in self.ptc.am) and hr == 12:
01019                     sourceTime = (yr, mth, dy, 0, mn, sec, wd, yd, isdst)
01020 
01021                   # if 'pm' found and hour < 12, add 12 to shift to evening
01022                 if (meridian in self.ptc.pm) and hr < 12:
01023                     sourceTime = (yr, mth, dy, hr + 12, mn, sec, wd, yd, isdst)
01024 
01025               # invalid time
01026             if hr > 24 or mn > 59 or sec > 59:
01027                 sourceTime    = now
01028                 self.dateFlag = 0
01029                 self.timeFlag = 0
01030 
01031             self.meridianFlag = False
01032 
01033           # Given string is in the format HH:MM(:SS)
01034         if self.timeStdFlag:
01035             if sourceTime is None:
01036                 (yr, mth, dy, hr, mn, sec, wd, yd, isdst) = now
01037             else:
01038                 (yr, mth, dy, hr, mn, sec, wd, yd, isdst) = sourceTime
01039 
01040             m = self.ptc.CRE_TIMEHMS.search(s)
01041             if m is not None:
01042                 hr, mn, sec = _extract_time(m)
01043             if hr == 24:
01044                 hr = 0
01045 
01046             if hr > 24 or mn > 59 or sec > 59:
01047                 # invalid time
01048                 sourceTime    = now
01049                 self.dateFlag = 0
01050                 self.timeFlag = 0
01051             else:
01052                 sourceTime = (yr, mth, dy, hr, mn, sec, wd, yd, isdst)
01053 
01054             self.timeStdFlag = False
01055 
01056         # Given string is in the format 07/21/2006
01057         if self.dateStdFlag:
01058             sourceTime       = self.parseDate(s)
01059             self.dateStdFlag = False
01060 
01061         # Given string is in the format  "May 23rd, 2005"
01062         if self.dateStrFlag:
01063             sourceTime       = self.parseDateText(s)
01064             self.dateStrFlag = False
01065 
01066         # Given string is a weekday
01067         if self.weekdyFlag:
01068             (yr, mth, dy, hr, mn, sec, wd, yd, isdst) = now
01069 
01070             start = datetime.datetime(yr, mth, dy, hr, mn, sec)
01071             wkdy  = self.ptc.WeekdayOffsets[s]
01072 
01073             if wkdy > wd:
01074                 qty = self._CalculateDOWDelta(wd, wkdy, 2,
01075                                               self.ptc.DOWParseStyle,
01076                                               self.ptc.CurrentDOWParseStyle)
01077             else:
01078                 qty = self._CalculateDOWDelta(wd, wkdy, 2,
01079                                               self.ptc.DOWParseStyle,
01080                                               self.ptc.CurrentDOWParseStyle)
01081 
01082             target = start + datetime.timedelta(days=qty)
01083             wd     = wkdy
01084 
01085             sourceTime      = target.timetuple()
01086             self.weekdyFlag = False
01087 
01088         # Given string is a natural language time string like
01089         # lunch, midnight, etc
01090         if self.timeStrFlag:
01091             if s in self.ptc.re_values['now']:
01092                 sourceTime = now
01093             else:
01094                 sources = self.ptc.buildSources(sourceTime)
01095 
01096                 if s in sources:
01097                     sourceTime = sources[s]
01098                 else:
01099                     sourceTime    = now
01100                     self.dateFlag = 0
01101                     self.timeFlag = 0
01102 
01103             self.timeStrFlag = False
01104 
01105         # Given string is a natural language date string like today, tomorrow..
01106         if self.dayStrFlag:
01107             if sourceTime is None:
01108                 sourceTime = now
01109 
01110             (yr, mth, dy, hr, mn, sec, wd, yd, isdst) = sourceTime
01111 
01112             if s in self.ptc.dayOffsets:
01113                 offset = self.ptc.dayOffsets[s]
01114             else:
01115                 offset = 0
01116 
01117             start      = datetime.datetime(yr, mth, dy, 9, 0, 0)
01118             target     = start + datetime.timedelta(days=offset)
01119             sourceTime = target.timetuple()
01120 
01121             self.dayStrFlag = False
01122 
01123         # Given string is a time string with units like "5 hrs 30 min"
01124         if self.unitsFlag:
01125             modifier = ''  # TODO
01126 
01127             if sourceTime is None:
01128                 sourceTime = now
01129 
01130             m = self.ptc.CRE_UNITS.search(s)
01131             if m is not None:
01132                 units    = m.group('units')
01133                 quantity = s[:m.start('units')]
01134 
01135             sourceTime     = self._buildTime(sourceTime, quantity, modifier, units)
01136             self.unitsFlag = False
01137 
01138         # Given string is a time string with single char units like "5 h 30 m"
01139         if self.qunitsFlag:
01140             modifier = ''  # TODO
01141 
01142             if sourceTime is None:
01143                 sourceTime = now
01144 
01145             m = self.ptc.CRE_QUNITS.search(s)
01146             if m is not None:
01147                 units    = m.group('qunits')
01148                 quantity = s[:m.start('qunits')]
01149 
01150             sourceTime      = self._buildTime(sourceTime, quantity, modifier, units)
01151             self.qunitsFlag = False
01152 
01153           # Given string does not match anything
01154         if sourceTime is None:
01155             sourceTime    = now
01156             self.dateFlag = 0
01157             self.timeFlag = 0
01158 
01159         return sourceTime
01160 

Here is the call graph for this function:

Here is the caller graph for this function:

def MoinMoin.support.parsedatetime.parsedatetime.Calendar.evalRanges (   self,
  datetimeString,
  sourceTime = None 
)
Evaluate the C{datetimeString} text and determine if
it represents a date or time range.

@type  datetimeString: string
@param datetimeString: datetime text to evaluate
@type  sourceTime:     struct_time
@param sourceTime:     C{struct_time} value to use as the base

@rtype:  tuple
@return: tuple of: start datetime, end datetime and the invalid flag

Definition at line 443 of file parsedatetime.py.

00443 
00444     def evalRanges(self, datetimeString, sourceTime=None):
00445         """
00446         Evaluate the C{datetimeString} text and determine if
00447         it represents a date or time range.
00448 
00449         @type  datetimeString: string
00450         @param datetimeString: datetime text to evaluate
00451         @type  sourceTime:     struct_time
00452         @param sourceTime:     C{struct_time} value to use as the base
00453 
00454         @rtype:  tuple
00455         @return: tuple of: start datetime, end datetime and the invalid flag
00456         """
00457         startTime = ''
00458         endTime   = ''
00459         startDate = ''
00460         endDate   = ''
00461         rangeFlag = 0
00462 
00463         s = datetimeString.strip().lower()
00464 
00465         if self.ptc.rangeSep in s:
00466             s = s.replace(self.ptc.rangeSep, ' %s ' % self.ptc.rangeSep)
00467             s = s.replace('  ', ' ')
00468 
00469         m = self.ptc.CRE_TIMERNG1.search(s)
00470         if m is not None:
00471             rangeFlag = 1
00472         else:
00473             m = self.ptc.CRE_TIMERNG2.search(s)
00474             if m is not None:
00475                 rangeFlag = 2
00476             else:
00477                 m = self.ptc.CRE_TIMERNG4.search(s)
00478                 if m is not None:
00479                     rangeFlag = 7
00480                 else:
00481                     m = self.ptc.CRE_TIMERNG3.search(s)
00482                     if m is not None:
00483                         rangeFlag = 3
00484                     else:
00485                         m = self.ptc.CRE_DATERNG1.search(s)
00486                         if m is not None:
00487                             rangeFlag = 4
00488                         else:
00489                             m = self.ptc.CRE_DATERNG2.search(s)
00490                             if m is not None:
00491                                 rangeFlag = 5
00492                             else:
00493                                 m = self.ptc.CRE_DATERNG3.search(s)
00494                                 if m is not None:
00495                                     rangeFlag = 6
00496 
00497         if _debug:
00498             print 'evalRanges: rangeFlag =', rangeFlag, '[%s]' % s
00499 
00500         if m is not None:
00501             if (m.group() != s):
00502                 # capture remaining string
00503                 parseStr = m.group()
00504                 chunk1   = s[:m.start()]
00505                 chunk2   = s[m.end():]
00506                 s        = '%s %s' % (chunk1, chunk2)
00507                 flag     = 1
00508 
00509                 sourceTime, flag = self.parse(s, sourceTime)
00510 
00511                 if flag == 0:
00512                     sourceTime = None
00513             else:
00514                 parseStr = s
00515 
00516         if rangeFlag == 1:
00517             m                = re.search(self.ptc.rangeSep, parseStr)
00518             startTime, sflag = self.parse((parseStr[:m.start()]),       sourceTime)
00519             endTime, eflag   = self.parse((parseStr[(m.start() + 1):]), sourceTime)
00520 
00521             if (eflag != 0)  and (sflag != 0):
00522                 return (startTime, endTime, 2)
00523 
00524         elif rangeFlag == 2:
00525             m                = re.search(self.ptc.rangeSep, parseStr)
00526             startTime, sflag = self.parse((parseStr[:m.start()]),       sourceTime)
00527             endTime, eflag   = self.parse((parseStr[(m.start() + 1):]), sourceTime)
00528 
00529             if (eflag != 0)  and (sflag != 0):
00530                 return (startTime, endTime, 2)
00531 
00532         elif rangeFlag == 3 or rangeFlag == 7:
00533             m = re.search(self.ptc.rangeSep, parseStr)
00534             # capturing the meridian from the end time
00535             if self.ptc.usesMeridian:
00536                 ampm = re.search(self.ptc.am[0], parseStr)
00537 
00538                 # appending the meridian to the start time
00539                 if ampm is not None:
00540                     startTime, sflag = self.parse((parseStr[:m.start()] + self.ptc.meridian[0]), sourceTime)
00541                 else:
00542                     startTime, sflag = self.parse((parseStr[:m.start()] + self.ptc.meridian[1]), sourceTime)
00543             else:
00544                 startTime, sflag = self.parse((parseStr[:m.start()]), sourceTime)
00545 
00546             endTime, eflag = self.parse(parseStr[(m.start() + 1):], sourceTime)
00547 
00548             if (eflag != 0)  and (sflag != 0):
00549                 return (startTime, endTime, 2)
00550 
00551         elif rangeFlag == 4:
00552             m                = re.search(self.ptc.rangeSep, parseStr)
00553             startDate, sflag = self.parse((parseStr[:m.start()]),       sourceTime)
00554             endDate, eflag   = self.parse((parseStr[(m.start() + 1):]), sourceTime)
00555 
00556             if (eflag != 0)  and (sflag != 0):
00557                 return (startDate, endDate, 1)
00558 
00559         elif rangeFlag == 5:
00560             m       = re.search(self.ptc.rangeSep, parseStr)
00561             endDate = parseStr[(m.start() + 1):]
00562 
00563             # capturing the year from the end date
00564             date    = self.ptc.CRE_DATE3.search(endDate)
00565             endYear = date.group('year')
00566 
00567             # appending the year to the start date if the start date
00568             # does not have year information and the end date does.
00569             # eg : "Aug 21 - Sep 4, 2007"
00570             if endYear is not None:
00571                 startDate = (parseStr[:m.start()]).strip()
00572                 date      = self.ptc.CRE_DATE3.search(startDate)
00573                 startYear = date.group('year')
00574 
00575                 if startYear is None:
00576                     startDate = startDate + ', ' + endYear
00577             else:
00578                 startDate = parseStr[:m.start()]
00579 
00580             startDate, sflag = self.parse(startDate, sourceTime)
00581             endDate, eflag   = self.parse(endDate, sourceTime)
00582 
00583             if (eflag != 0)  and (sflag != 0):
00584                 return (startDate, endDate, 1)
00585 
00586         elif rangeFlag == 6:
00587             m = re.search(self.ptc.rangeSep, parseStr)
00588 
00589             startDate = parseStr[:m.start()]
00590 
00591             # capturing the month from the start date
00592             mth = self.ptc.CRE_DATE3.search(startDate)
00593             mth = mth.group('mthname')
00594 
00595             # appending the month name to the end date
00596             endDate = mth + parseStr[(m.start() + 1):]
00597 
00598             startDate, sflag = self.parse(startDate, sourceTime)
00599             endDate, eflag   = self.parse(endDate, sourceTime)
00600 
00601             if (eflag != 0)  and (sflag != 0):
00602                 return (startDate, endDate, 1)
00603         else:
00604             # if range is not found
00605             sourceTime = time.localtime()
00606 
00607             return (sourceTime, sourceTime, 0)
00608 

Here is the call graph for this function:

def MoinMoin.support.parsedatetime.parsedatetime.Calendar.inc (   self,
  source,
  month = None,
  year = None 
)
Takes the given C{source} date, or current date if none is
passed, and increments it according to the values passed in
by month and/or year.

This routine is needed because Python's C{timedelta()} function
does not allow for month or year increments.

@type  source: struct_time
@param source: C{struct_time} value to increment
@type  month:  integer
@param month:  optional number of months to increment
@type  year:   integer
@param year:   optional number of years to increment

@rtype:  datetime
@return: C{source} incremented by the number of months and/or years

Definition at line 1479 of file parsedatetime.py.

01479 
01480     def inc(self, source, month=None, year=None):
01481         """
01482         Takes the given C{source} date, or current date if none is
01483         passed, and increments it according to the values passed in
01484         by month and/or year.
01485 
01486         This routine is needed because Python's C{timedelta()} function
01487         does not allow for month or year increments.
01488 
01489         @type  source: struct_time
01490         @param source: C{struct_time} value to increment
01491         @type  month:  integer
01492         @param month:  optional number of months to increment
01493         @type  year:   integer
01494         @param year:   optional number of years to increment
01495 
01496         @rtype:  datetime
01497         @return: C{source} incremented by the number of months and/or years
01498         """
01499         yr  = source.year
01500         mth = source.month
01501         dy  = source.day
01502 
01503         if year:
01504             try:
01505                 yi = int(year)
01506             except ValueError:
01507                 yi = 0
01508 
01509             yr += yi
01510 
01511         if month:
01512             try:
01513                 mi = int(month)
01514             except ValueError:
01515                 mi = 0
01516 
01517             m = abs(mi)
01518             y = m / 12      # how many years are in month increment
01519             m = m % 12      # get remaining months
01520 
01521             if mi < 0:
01522                 mth = mth - m           # sub months from start month
01523                 if mth < 1:             # cross start-of-year?
01524                     y   -= 1            #   yes - decrement year
01525                     mth += 12           #         and fix month
01526             else:
01527                 mth = mth + m           # add months to start month
01528                 if mth > 12:            # cross end-of-year?
01529                     y   += 1            #   yes - increment year
01530                     mth -= 12           #         and fix month
01531 
01532             yr += y
01533 
01534             # if the day ends up past the last day of
01535             # the new month, set it to the last day
01536             if dy > self.ptc.daysInMonth(mth, yr):
01537                 dy = self.ptc.daysInMonth(mth, yr)
01538 
01539         d = source.replace(year=yr, month=mth, day=dy)
01540 
01541         return source + (d - source)
01542 

Here is the caller graph for this function:

def MoinMoin.support.parsedatetime.parsedatetime.Calendar.parse (   self,
  datetimeString,
  sourceTime = None 
)
Splits the given C{datetimeString} into tokens, finds the regex
patterns that match and then calculates a C{struct_time} value from
the chunks.

If C{sourceTime} is given then the C{struct_time} value will be
calculated from that value, otherwise from the current date/time.

If the C{datetimeString} is parsed and date/time value found then
the second item of the returned tuple will be a flag to let you know
what kind of C{struct_time} value is being returned::

    0 = not parsed at all
    1 = parsed as a C{date}
    2 = parsed as a C{time}
    3 = parsed as a C{datetime}

@type  datetimeString: string
@param datetimeString: date/time text to evaluate
@type  sourceTime:     struct_time
@param sourceTime:     C{struct_time} value to use as the base

@rtype:  tuple
@return: tuple of: modified C{sourceTime} and the result flag

Definition at line 1161 of file parsedatetime.py.

01161 
01162     def parse(self, datetimeString, sourceTime=None):
01163         """
01164         Splits the given C{datetimeString} into tokens, finds the regex
01165         patterns that match and then calculates a C{struct_time} value from
01166         the chunks.
01167 
01168         If C{sourceTime} is given then the C{struct_time} value will be
01169         calculated from that value, otherwise from the current date/time.
01170 
01171         If the C{datetimeString} is parsed and date/time value found then
01172         the second item of the returned tuple will be a flag to let you know
01173         what kind of C{struct_time} value is being returned::
01174 
01175             0 = not parsed at all
01176             1 = parsed as a C{date}
01177             2 = parsed as a C{time}
01178             3 = parsed as a C{datetime}
01179 
01180         @type  datetimeString: string
01181         @param datetimeString: date/time text to evaluate
01182         @type  sourceTime:     struct_time
01183         @param sourceTime:     C{struct_time} value to use as the base
01184 
01185         @rtype:  tuple
01186         @return: tuple of: modified C{sourceTime} and the result flag
01187         """
01188 
01189         if sourceTime:
01190             if isinstance(sourceTime, datetime.datetime):
01191                 if _debug:
01192                     print 'coercing datetime to timetuple'
01193                 sourceTime = sourceTime.timetuple()
01194             else:
01195                 if not isinstance(sourceTime, time.struct_time) and \
01196                    not isinstance(sourceTime, tuple):
01197                     raise Exception('sourceTime is not a struct_time')
01198 
01199         s         = datetimeString.strip().lower()
01200         parseStr  = ''
01201         totalTime = sourceTime
01202 
01203         if s == '' :
01204             if sourceTime is not None:
01205                 return (sourceTime, self.dateFlag + self.timeFlag)
01206             else:
01207                 return (time.localtime(), 0)
01208 
01209         self.timeFlag = 0
01210         self.dateFlag = 0
01211 
01212         while len(s) > 0:
01213             flag   = False
01214             chunk1 = ''
01215             chunk2 = ''
01216 
01217             if _debug:
01218                 print 'parse (top of loop): [%s][%s]' % (s, parseStr)
01219 
01220             if parseStr == '':
01221                 # Modifier like next\prev..
01222                 m = self.ptc.CRE_MODIFIER.search(s)
01223                 if m is not None:
01224                     self.modifierFlag = True
01225                     if (m.group('modifier') != s):
01226                         # capture remaining string
01227                         parseStr = m.group('modifier')
01228                         chunk1   = s[:m.start('modifier')].strip()
01229                         chunk2   = s[m.end('modifier'):].strip()
01230                         flag     = True
01231                     else:
01232                         parseStr = s
01233 
01234             if parseStr == '':
01235                 # Modifier like from\after\prior..
01236                 m = self.ptc.CRE_MODIFIER2.search(s)
01237                 if m is not None:
01238                     self.modifier2Flag = True
01239                     if (m.group('modifier') != s):
01240                         # capture remaining string
01241                         parseStr = m.group('modifier')
01242                         chunk1   = s[:m.start('modifier')].strip()
01243                         chunk2   = s[m.end('modifier'):].strip()
01244                         flag     = True
01245                     else:
01246                         parseStr = s
01247 
01248             if parseStr == '':
01249                 valid_date = False
01250                 for match in self.ptc.CRE_DATE3.finditer(s):
01251                     # to prevent "HH:MM(:SS) time strings" expressions from triggering
01252                     # this regex, we checks if the month field exists in the searched 
01253                     # expression, if it doesn't exist, the date field is not valid
01254                     if match.group('mthname'):
01255                         m = self.ptc.CRE_DATE3.search(s, match.start())
01256                         valid_date = True
01257                         break
01258 
01259                 # String date format
01260                 if valid_date:
01261                     self.dateStrFlag = True
01262                     self.dateFlag    = 1
01263                     if (m.group('date') != s):
01264                         # capture remaining string
01265                         parseStr = m.group('date')
01266                         chunk1   = s[:m.start('date')]
01267                         chunk2   = s[m.end('date'):]
01268                         s        = '%s %s' % (chunk1, chunk2)
01269                         flag     = True
01270                     else:
01271                         parseStr = s
01272 
01273             if parseStr == '':
01274                 # Standard date format
01275                 m = self.ptc.CRE_DATE.search(s)
01276                 if m is not None:
01277                     self.dateStdFlag = True
01278                     self.dateFlag    = 1
01279                     if (m.group('date') != s):
01280                         # capture remaining string
01281                         parseStr = m.group('date')
01282                         chunk1   = s[:m.start('date')]
01283                         chunk2   = s[m.end('date'):]
01284                         s        = '%s %s' % (chunk1, chunk2)
01285                         flag     = True
01286                     else:
01287                         parseStr = s
01288 
01289             if parseStr == '':
01290                 # Natural language day strings
01291                 m = self.ptc.CRE_DAY.search(s)
01292                 if m is not None:
01293                     self.dayStrFlag = True
01294                     self.dateFlag   = 1
01295                     if (m.group('day') != s):
01296                         # capture remaining string
01297                         parseStr = m.group('day')
01298                         chunk1   = s[:m.start('day')]
01299                         chunk2   = s[m.end('day'):]
01300                         s        = '%s %s' % (chunk1, chunk2)
01301                         flag     = True
01302                     else:
01303                         parseStr = s
01304 
01305             if parseStr == '':
01306                 # Quantity + Units
01307                 m = self.ptc.CRE_UNITS.search(s)
01308                 if m is not None:
01309                     self.unitsFlag = True
01310                     if (m.group('qty') != s):
01311                         # capture remaining string
01312                         parseStr = m.group('qty')
01313                         chunk1   = s[:m.start('qty')].strip()
01314                         chunk2   = s[m.end('qty'):].strip()
01315 
01316                         if chunk1[-1:] == '-':
01317                             parseStr = '-%s' % parseStr
01318                             chunk1   = chunk1[:-1]
01319 
01320                         s    = '%s %s' % (chunk1, chunk2)
01321                         flag = True
01322                     else:
01323                         parseStr = s
01324 
01325             if parseStr == '':
01326                 # Quantity + Units
01327                 m = self.ptc.CRE_QUNITS.search(s)
01328                 if m is not None:
01329                     self.qunitsFlag = True
01330 
01331                     if (m.group('qty') != s):
01332                         # capture remaining string
01333                         parseStr = m.group('qty')
01334                         chunk1   = s[:m.start('qty')].strip()
01335                         chunk2   = s[m.end('qty'):].strip()
01336 
01337                         if chunk1[-1:] == '-':
01338                             parseStr = '-%s' % parseStr
01339                             chunk1   = chunk1[:-1]
01340 
01341                         s    = '%s %s' % (chunk1, chunk2)
01342                         flag = True
01343                     else:
01344                         parseStr = s 
01345 
01346             if parseStr == '':
01347                 # Weekday
01348                 m = self.ptc.CRE_WEEKDAY.search(s)
01349                 if m is not None:
01350                     gv = m.group('weekday')
01351                     if s not in self.ptc.dayOffsets:
01352                         self.weekdyFlag = True
01353                         self.dateFlag   = 1
01354                         if (gv != s):
01355                             # capture remaining string
01356                             parseStr = gv
01357                             chunk1   = s[:m.start('weekday')]
01358                             chunk2   = s[m.end('weekday'):]
01359                             s        = '%s %s' % (chunk1, chunk2)
01360                             flag     = True
01361                         else:
01362                             parseStr = s
01363 
01364             if parseStr == '':
01365                 # Natural language time strings
01366                 m = self.ptc.CRE_TIME.search(s)
01367                 if m is not None:
01368                     self.timeStrFlag = True
01369                     self.timeFlag    = 2
01370                     if (m.group('time') != s):
01371                         # capture remaining string
01372                         parseStr = m.group('time')
01373                         chunk1   = s[:m.start('time')]
01374                         chunk2   = s[m.end('time'):]
01375                         s        = '%s %s' % (chunk1, chunk2)
01376                         flag     = True
01377                     else:
01378                         parseStr = s
01379 
01380             if parseStr == '':
01381                 # HH:MM(:SS) am/pm time strings
01382                 m = self.ptc.CRE_TIMEHMS2.search(s)
01383                 if m is not None:
01384                     self.meridianFlag = True
01385                     self.timeFlag     = 2
01386                     if m.group('minutes') is not None:
01387                         if m.group('seconds') is not None:
01388                             parseStr = '%s:%s:%s %s' % (m.group('hours'),
01389                                                         m.group('minutes'),
01390                                                         m.group('seconds'),
01391                                                         m.group('meridian'))
01392                         else:
01393                             parseStr = '%s:%s %s' % (m.group('hours'),
01394                                                      m.group('minutes'),
01395                                                      m.group('meridian'))
01396                     else:
01397                         parseStr = '%s %s' % (m.group('hours'),
01398                                               m.group('meridian'))
01399 
01400                     chunk1 = s[:m.start('hours')]
01401                     chunk2 = s[m.end('meridian'):]
01402 
01403                     s    = '%s %s' % (chunk1, chunk2)
01404                     flag = True
01405 
01406             if parseStr == '':
01407                 # HH:MM(:SS) time strings
01408                 m = self.ptc.CRE_TIMEHMS.search(s)
01409                 if m is not None:
01410                     self.timeStdFlag = True
01411                     self.timeFlag    = 2
01412                     if m.group('seconds') is not None:
01413                         parseStr = '%s:%s:%s' % (m.group('hours'),
01414                                                  m.group('minutes'),
01415                                                  m.group('seconds'))
01416                         chunk1   = s[:m.start('hours')]
01417                         chunk2   = s[m.end('seconds'):]
01418                     else:
01419                         parseStr = '%s:%s' % (m.group('hours'),
01420                                               m.group('minutes'))
01421                         chunk1   = s[:m.start('hours')]
01422                         chunk2   = s[m.end('minutes'):]
01423 
01424                     s    = '%s %s' % (chunk1, chunk2)
01425                     flag = True
01426 
01427             # if string does not match any regex, empty string to
01428             # come out of the while loop
01429             if not flag:
01430                 s = ''
01431 
01432             if _debug:
01433                 print 'parse (bottom) [%s][%s][%s][%s]' % (s, parseStr, chunk1, chunk2)
01434                 print 'weekday %s, dateStd %s, dateStr %s, time %s, timeStr %s, meridian %s' % \
01435                        (self.weekdyFlag, self.dateStdFlag, self.dateStrFlag, self.timeStdFlag, self.timeStrFlag, self.meridianFlag)
01436                 print 'dayStr %s, modifier %s, modifier2 %s, units %s, qunits %s' % \
01437                        (self.dayStrFlag, self.modifierFlag, self.modifier2Flag, self.unitsFlag, self.qunitsFlag)
01438 
01439             # evaluate the matched string
01440             if parseStr != '':
01441                 if self.modifierFlag == True:
01442                     t, totalTime = self._evalModifier(parseStr, chunk1, chunk2, totalTime)
01443                     # t is the unparsed part of the chunks.
01444                     # If it is not date/time, return current
01445                     # totalTime as it is; else return the output
01446                     # after parsing t.
01447                     if (t != '') and (t != None):
01448                         tempDateFlag       = self.dateFlag
01449                         tempTimeFlag       = self.timeFlag
01450                         (totalTime2, flag) = self.parse(t, totalTime)
01451 
01452                         if flag == 0 and totalTime is not None:
01453                             self.timeFlag = tempTimeFlag
01454                             self.dateFlag = tempDateFlag
01455 
01456                             return (totalTime, self.dateFlag + self.timeFlag)
01457                         else:
01458                             return (totalTime2, self.dateFlag + self.timeFlag)
01459 
01460                 elif self.modifier2Flag == True:
01461                     totalTime, invalidFlag = self._evalModifier2(parseStr, chunk1, chunk2, totalTime)
01462 
01463                     if invalidFlag == True:
01464                         self.dateFlag = 0
01465                         self.timeFlag = 0
01466 
01467                 else:
01468                     totalTime = self._evalString(parseStr, totalTime)
01469                     parseStr  = ''
01470 
01471         # String is not parsed at all
01472         if totalTime is None or totalTime == sourceTime:
01473             totalTime     = time.localtime()
01474             self.dateFlag = 0
01475             self.timeFlag = 0
01476 
01477         return (totalTime, self.dateFlag + self.timeFlag)
01478 

Here is the call graph for this function:

Here is the caller graph for this function:

Parse short-form date strings::

    '05/28/2006' or '04.21'

@type  dateString: string
@param dateString: text to convert to a C{datetime}

@rtype:  struct_time
@return: calculated C{struct_time} value of dateString

Definition at line 312 of file parsedatetime.py.

00312 
00313     def parseDate(self, dateString):
00314         """
00315         Parse short-form date strings::
00316 
00317             '05/28/2006' or '04.21'
00318 
00319         @type  dateString: string
00320         @param dateString: text to convert to a C{datetime}
00321 
00322         @rtype:  struct_time
00323         @return: calculated C{struct_time} value of dateString
00324         """
00325         yr, mth, dy, hr, mn, sec, wd, yd, isdst = time.localtime()
00326 
00327         # values pulled from regex's will be stored here and later
00328         # assigned to mth, dy, yr based on information from the locale
00329         # -1 is used as the marker value because we want zero values
00330         # to be passed thru so they can be flagged as errors later
00331         v1 = -1
00332         v2 = -1
00333         v3 = -1
00334 
00335         s = dateString
00336         m = self.ptc.CRE_DATE2.search(s)
00337         if m is not None:
00338             index = m.start()
00339             v1    = int(s[:index])
00340             s     = s[index + 1:]
00341 
00342         m = self.ptc.CRE_DATE2.search(s)
00343         if m is not None:
00344             index = m.start()
00345             v2    = int(s[:index])
00346             v3    = int(s[index + 1:])
00347         else:
00348             v2 = int(s.strip())
00349 
00350         v = [ v1, v2, v3 ]
00351         d = { 'm': mth, 'd': dy, 'y': yr }
00352 
00353         for i in range(0, 3):
00354             n = v[i]
00355             c = self.ptc.dp_order[i]
00356             if n >= 0:
00357                 d[c] = n
00358 
00359         # if the year is not specified and the date has already
00360         # passed, increment the year
00361         if v3 == -1 and ((mth > d['m']) or (mth == d['m'] and dy > d['d'])):
00362             yr = d['y'] + 1
00363         else:
00364             yr  = d['y']
00365 
00366         mth = d['m']
00367         dy  = d['d']
00368 
00369         # birthday epoch constraint
00370         if yr < self.ptc.BirthdayEpoch:
00371             yr += 2000
00372         elif yr < 100:
00373             yr += 1900
00374 
00375         if _debug:
00376             print 'parseDate: ', yr, mth, dy, self.ptc.daysInMonth(mth, yr)
00377 
00378         if (mth > 0 and mth <= 12) and \
00379            (dy > 0 and dy <= self.ptc.daysInMonth(mth, yr)):
00380             sourceTime = (yr, mth, dy, hr, mn, sec, wd, yd, isdst)
00381         else:
00382             self.dateFlag = 0
00383             self.timeFlag = 0
00384             sourceTime    = time.localtime() # return current time if date
00385                                              # string is invalid
00386 
00387         return sourceTime
00388 

Here is the caller graph for this function:

Parse long-form date strings::

    'May 31st, 2006'
    'Jan 1st'
    'July 2006'

@type  dateString: string
@param dateString: text to convert to a datetime

@rtype:  struct_time
@return: calculated C{struct_time} value of dateString

Definition at line 389 of file parsedatetime.py.

00389 
00390     def parseDateText(self, dateString):
00391         """
00392         Parse long-form date strings::
00393 
00394             'May 31st, 2006'
00395             'Jan 1st'
00396             'July 2006'
00397 
00398         @type  dateString: string
00399         @param dateString: text to convert to a datetime
00400 
00401         @rtype:  struct_time
00402         @return: calculated C{struct_time} value of dateString
00403         """
00404         yr, mth, dy, hr, mn, sec, wd, yd, isdst = time.localtime()
00405 
00406         currentMth = mth
00407         currentDy  = dy
00408 
00409         s   = dateString.lower()
00410         m   = self.ptc.CRE_DATE3.search(s)
00411         mth = m.group('mthname')
00412         mth = self.ptc.MonthOffsets[mth]
00413 
00414         if m.group('day') !=  None:
00415             dy = int(m.group('day'))
00416         else:
00417             dy = 1
00418 
00419         if m.group('year') !=  None:
00420             yr = int(m.group('year'))
00421 
00422             # birthday epoch constraint
00423             if yr < self.ptc.BirthdayEpoch:
00424                 yr += 2000
00425             elif yr < 100:
00426                 yr += 1900
00427 
00428         elif (mth < currentMth) or (mth == currentMth and dy < currentDy):
00429             # if that day and month have already passed in this year,
00430             # then increment the year by 1
00431             yr += 1
00432 
00433         if dy > 0 and dy <= self.ptc.daysInMonth(mth, yr):
00434             sourceTime = (yr, mth, dy, hr, mn, sec, wd, yd, isdst)
00435         else:
00436             # Return current time if date string is invalid
00437             self.dateFlag = 0
00438             self.timeFlag = 0
00439             sourceTime    = time.localtime()
00440 
00441         return sourceTime
00442 

Here is the caller graph for this function:


Member Data Documentation

Definition at line 214 of file parsedatetime.py.

Definition at line 202 of file parsedatetime.py.

Definition at line 203 of file parsedatetime.py.

Definition at line 206 of file parsedatetime.py.

Definition at line 205 of file parsedatetime.py.

Definition at line 209 of file parsedatetime.py.

Definition at line 208 of file parsedatetime.py.

Definition at line 197 of file parsedatetime.py.

Definition at line 211 of file parsedatetime.py.

Definition at line 213 of file parsedatetime.py.

Definition at line 204 of file parsedatetime.py.

Definition at line 207 of file parsedatetime.py.

Definition at line 210 of file parsedatetime.py.

Definition at line 201 of file parsedatetime.py.


The documentation for this class was generated from the following file: