[Python-ideas] Pythonic Dates, Times, and Deltas

Daniel G. Taylor danielgtaylor at gmail.com
Thu Oct 14 20:51:05 CEST 2010


On 10/14/2010 08:06 AM, Masklinn wrote:
> On 2010-10-14, at 10:02 , Marco Mariani wrote:
>> On 13 October 2010 23:17, Alexander Belopolsky<
>> alexander.belopolsky at gmail.com>  wrote:
>> * Make it easy to get a tuple of the start and end of the month
>>>
>>> Why would you want this?  Start of the month is easy: just date(year,
>>> month, 1).  End of the month is often unnecessary because it is more
>>> pythonic to work with semi-open ranges and use first of the next month
>>> instead.
>>
>> Except next month may well be in next year.. blah
>>
>> And I don't care about pythonic ranges if I have to push the values through
>> a BETWEEN query in SQL.
>>
>> import calendar
>> import datetime
>>
>> end = datetime.date(year, month, calendar.monthrange(year, month)[1])
>
> There's also dateutil, which exposes some ideas of mx.DateTime on top of the built-in datetime, including relativedelta.
>
> As a result, you can get the last day of the current month by going backwards one day from the first day of next month:
>
>>>> datetime.now().date() + relativedelta(months=+1, day=+1, days=-1)
> datetime.date(2010, 10, 31)
>
> Or (clearer order of operations):
>
>>>> datetime.now().date() + relativedelta(months=+1, day=+1) + relativedelta(days=-1)
> datetime.date(2010, 10, 31)
>
> (note that in both cases the "+" sign is of course optional).
>
> Parameters without an `s` postfix are absolute (day=1 sets the day of the current datetime to 1, similar to using .replace), parameters with an `s` are offsets (`days=+1` takes tomorrow).

FWIW my library does the same sort of stuff using relativedelta 
internally, just sugar coats it heavily ;-)

Take care,
-- 
Daniel G. Taylor
http://programmer-art.org/



More information about the Python-ideas mailing list