Add a month

Carsten Haese carsten at uniqsys.com
Fri Feb 17 16:38:38 EST 2006


On Fri, 2006-02-17 at 16:10, Gregory Piñero wrote:
> Actually, no wait, that's bad.  It doesn't increment the year.
> 
> Does anyone have a simple way to code this?
> 
> -Greg
> 
> 
> On 2/17/06, Gregory Piñero <gregpinero at gmail.com> wrote:
> > Here's how I do it:
> >
> > def monthify(anint):
> >     if anint%12==0:return 12
> >     else:return anint%12
> >
> > import datetime
> > d=datetime.datetime.today()
> > dplus1month=datetime.datetime(d.year,monthify(d.month+1),d.day)
> >
> > We need monthify because adding 1 to 12 is bad otherwise!
> >
> > -Greg
> >
> > On 17 Feb 2006 04:15:39 -0800, Paul Boddie <paul at boddie.org.uk> wrote:
> > > Fredrik Lundh wrote:
> > > >
> > > > what do you expect d_new to be after the operation ?  if the answer
> > > > is date(2006,3,17), what's date(2006,1,31) plus one month?
> > >
> > > February 31st, of course:
> > >
> > > http://sql-info.de/mysql/gotchas.html#1_14
> > >
> > > ;-)
> > >
> > > Paul
> > >
> > > --
> > > http://mail.python.org/mailman/listinfo/python-list
> > >
> >
> >
> > --
> > Gregory Piñero
> > Chief Innovation Officer
> > Blended Technologies
> > (www.blendedtechnologies.com)
> >
> 
> 

I don't know if this qualifies as simple, but it seems to work:

def addmonths(thedate,months):
  "Add <months> months to <thedate>."
  import datetime
  y,m,d = thedate.timetuple()[:3]
  y2, m2 = divmod(m+months-1, 12)
  return datetime.date(y+y2,m2+1,d)

Note that the date constructor will raise an exception if the result
happens to be an invalid date such as February 30th or November 31st.

-Carsten





More information about the Python-list mailing list