Datetime utility functions
Paul.Moore at atosorigin.com
Tue Sep 16 17:46:59 CEST 2003
From: Gustavo Niemeyer [mailto:niemeyer at conectiva.com]
> Your message arrived in the exact time.. :-)
> 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...
>> 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 don't understand this one. The last day of the month containing
> a given datetime? A datetime is absolute, how would it be "contained"
> in something else?
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"
There isn't really a good way of getting "end". I can either add 1 month
(which involves splitting out the month and year, and handling the end of
year) and then subtracting 1 day, or I can try setting the day to 31, 30,
29, 28 in turn, and stop as soon as I don't get an exception.
Neither method is hard, it just seems like one of those tasks that should
With your "relativedelta" I could do this pretty easily, by
end = start + relativedelta(months=+1, days=-1)
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
More information about the Python-list