Datetime utility functions

Paul Moore paul.moore at atosorigin.com
Mon Sep 15 11:07:07 EDT 2003


I was just writing some code which did date/time manipulations, and I
found that the Python 2.3 datetime module does not supply a number of
fairly basic functions. I understand the reasoning (the datetime
module provides a set of datatypes, and doesn't attempt to get into
the murky waters of date algorithms) but as these things can be quite
tricky to get right, I was wondering if anyone has already implemented
any date algorithms, or alternatively if I'd missed some easy way of
doing what I'm after.

My specific requirements were:

1. Get the last day of the month contatining a given date(time). I
really was surprised to find this one missing, as it seems to me that
the datetime module must know what the last day for each month is, so
exposing it wouldn't have been hard.

2. Add a number of months to a date. This is messy, as there are
options (what is one month after 31st Jan). The trouble is that the
calculation, while simple, is tricky to get right (month is 1-based,
so off-by-1 errors are easy to make, and divmod isn't as useful as
you'd first think).

Other "nice to have" functions which I didn't need for this program,
but which I have found useful in the past, are

- Round a date(time) to a {year,month,day,quarter,week,...} Or
truncate. Or (occasionally) chop to the next higher boundary
(ceiling).
- Calculate the number of {years,months,days,...} between two dates.
(Which is more or less the equivalent of rounding a timedelta).

These latter two aren't very well defined right now, because I have no
immediate use case.

In the absence of anything else, I'll probably write a "date
utilities" module for myself at some point. But I'd hate to be
reinventing the wheel.

Paul.




More information about the Python-list mailing list