[Python-Dev] Issue5434: datetime.monthdelta
jess.austin at gmail.com
Thu Apr 16 08:18:01 CEST 2009
I'm new to python core development, and I've been advised to write to
python-dev concerning a feature/patch I've placed at
http://bugs.python.org/issue5434, with Rietveld at
This patch adds a "monthdelta" class and a "monthmod" function to the
datetime module. The monthdelta class is much like the existing
timedelta class, except that it represents months offset from a date,
rather than an exact period offset from a date. This allows us to
easily say, e.g. "3 months from now" without worrying about the number
of days in the intervening months.
>>> date(2008, 1, 30) + monthdelta(1)
datetime.date(2008, 2, 29)
>>> date(2008, 1, 30) + monthdelta(2)
datetime.date(2008, 3, 30)
The monthmod function, named in (imperfect) analogy to divmod, allows
us to round-trip by returning the interim between two dates
represented as a (monthdelta, timedelta) tuple:
>>> monthmod(date(2008, 1, 14), date(2009, 4, 2))
Invariant: dt + monthmod(dt, dt+td) + monthmod(dt, dt+td) == dt + td
These also work with datetimes! There are more details in the
documentation included in the patch. In addition to the C module
file, I've updated the datetime CAPI, the documentation, and tests.
I feel this would be a good addition to core python. In my work, I've
often ended up writing annoying one-off "add-a-month" or similar
functions. I think since months work differently than most other time
periods, a new object is justified rather than trying to shoe-horn
something like this into timedelta. I also think that the round-trip
functionality provided by monthmod is important to ensure that
monthdeltas are "first-class" objects.
Please let me know what you think of the idea and/or its execution.
More information about the Python-Dev