Datetime utility functions

Gustavo Niemeyer niemeyer at
Tue Sep 16 19:06:27 CEST 2003

> > Have a look at this:
> I like that. I'm not entirely happy with the name of the class, but as
> I can't come up with a better suggestion, I shouldn't criticise...

The name explains it pretty well. It's like timedelta, but it's
a "relative" delta, since how much it will advance will depend on
the date you apply it to.

> Sorry, I didn't explain that very well. Imagine an application to report
> stats over a period. The user can specify a date, and the report will be
> for a calendar month, containing the user's required date. So my code
> will be something like
>     start = user_date.replace(day=1) # Start of the month
>     end = "Last day of the month"

Oh! Ok.. I understand now.

> With your "relativedelta" I could do this pretty easily, by
>     end = start + relativedelta(months=+1, days=-1)

Hummm.. no. Look:

 >>>, days=-1), 10, 15)

Instead, it should be done by:

 >>>, day=31)

Notice that it works also for other months:

 >>>, day=31), 2, 28)

This is described in step 4 of the documentation I pasted
in the mail.

> but I still feel that I'd need to have an explanatory comment. The
> datetime module *knows* the number of days in the month - I'd just
> like it to tell *me*.

Have you noticed that this is also offered by the calendar module?

 >>> import calendar
 >>> calendar.monthrange(2003, 9)
 (0, 30)

Gustavo Niemeyer

More information about the Python-list mailing list