Datetime utility functions
niemeyer at conectiva.com
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:
>>> date.today()+relativedelta(months=+1, days=-1)
datetime.date(2003, 10, 15)
Instead, it should be done by:
>>> date.today()+relativedelta(months=+1, day=31)
Notice that it works also for other months:
>>> date.today()+relativedelta(month=2, day=31)
datetime.date(2003, 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)
More information about the Python-list