Datetime utility functions

John Roth newsgroups at jhrothjr.com
Mon Sep 15 18:04:48 CEST 2003


"Paul Moore" <paul.moore at atosorigin.com> wrote in message
news:182bcf76.0309150707.3a8c0482 at posting.google.com...
> 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.

I'm kind of surprised to see that it's missing, too.

> 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).

That's application dependent. If a bond, for example, has interest
payable on the 30th of the month, you probably want the 30th,
except in February you want the last day of the month. However,
the contract may specify something else. And in no case do you
want the date to suddenly change to the 28th because you went
through February.

> 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.

Most of these don't have well defined, globally useful use cases.
It's heavily application dependent what you want out of these.

> 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.

There's a very well regarded date module out there in the
Vaults of Parnassus. The name escapes me at the moment,
but a bit of spelunking through the Vaults will turn up several
date routines that may do what you want.

John Roth

>
> Paul.






More information about the Python-list mailing list