[Zope] Date addition in a Python script

complaw@hal-pc.org complaw@hal-pc.org
Wed, 16 Jan 2002 16:09:55 GMT


I ran into the same problem a few weeks ago.  Try this code, it isn't pretty,
but it has worked reliably so far.  Note, this code will back off on a day to
keep the month.  I.e., if you want one month after January 31, it will give you
February 28 (on a non-leap year) or February 29 (on a leap year):

#  Define the method for calculating X number of months ahead...
def DateAhead(theDate, num_months=0):
  dateStr       = str(theDate)
  startingYear  = dateStr[0:4]
  startingMonth = dateStr[5:7]
  startingDay   = dateStr[8:10]
  endingMonth   = int(startingMonth) + num_months
  endingYear    = int(startingYear)
  endingDay     = int(startingDay)
  #  Add years to correspond to the added months...
  while endingMonth > 12:
    endingYear  = endingYear + 1
    endingMonth = endingMonth - 12
  #  Check to make sure that the ending month has the requisite days...
  dateFound = 0
  while dateFound == 0:
    try:
      newDate = DateTime(str(endingYear) + '/' + str(endingMonth) + '/' +
str(endingDay))
      dateFound = 1 # If you got this far, the date must be good.
    except:
      endingDay = endingDay - 1
      dateFound = 0

  return newDate
    


> I'm trying to add an arbitrary number of months to a DateTime value, and
> keep running into problems.
> 
> My code looks like this:
> 
> -----
> ## Script (Python) "NewDate"
> ##bind container=container
> ##bind context=context
> ##bind namespace=
> ##bind script=script
> ##bind subpath=traverse_subpath
> ##parameters=Member, Effective_Date, Months_Added
> ##title=
> ##
> Old_Date = Member.PaidThrough
> Eff_Date = DateTime(Effective_Date)
> 
> if Eff_Date > Old_Date:
>   Old_Date = Eff_Date
> 
> Month = Old_Date.month()
> Day = Old_Date.day()
> Year = Old_Date.year()
> 
> NewDate = DateTime(Year,Month+int(Months_Added),Day)
> 
> return NewDate
> -----
> 
> The problem arises when DateTime() tries to create a new date out of values
> like 2002,21,15 (reached by adding 15 months to 2002-06-15).  Is there a way
> to coerce DateTime() to handle situations like this, or an algorithm for
> 'fixing' such date addition?
> 
> --- Chris Carlson
> 
> 
> _______________________________________________
> Zope maillist  -  Zope@zope.org
> http://lists.zope.org/mailman/listinfo/zope
> **   No cross posts or HTML encoding!  **
> (Related lists - 
>  http://lists.zope.org/mailman/listinfo/zope-announce
>  http://lists.zope.org/mailman/listinfo/zope-dev )
>