Datetime utility functions

Christos TZOTZIOY Georgiou tzot at sil-tec.gr
Tue Sep 16 16:15:24 CEST 2003


On 15 Sep 2003 08:07:07 -0700, rumours say that
paul.moore at atosorigin.com (Paul Moore) might have written:

[about missing datetime functionality]

>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 would guess that the simple ones were not included just because they
are only a few lines each:

def end_of_month(a_date):
   year_inc, month_inc = divmod(a_date.month, 12)
   return a_date.__class__(a_date.year+year_inc, 1+month_inc, 1) - \
       datetime.timedelta(days=1)

def month_days(a_date):
   return end_of_month(a_date).day

Examples:

>>> end_of_month(datetime.date.today())
datetime.date(2003, 9, 30)
>>> end_of_month(datetime.datetime(1972,2,11))
datetime.datetime(1972, 2, 29, 0, 0)
>>> month_days(datetime.date.today())
30
>>> end_of_month(datetime.date(1977,12,15))
datetime.date(1977, 12, 31)

The add_months_to_date seems not that hard too, but I don't have a need
for one so far, so I haven't coded it :)  My needs for datetime
intervals are usually of the 'one month start - another month end' kind,
so end_of_month is handy.  If you do think these would be useful, feel
free to use them (or your own versions) for a patch.

Date / timedelta rounding / truncating to various units would have to
take account of many different rules, and none would be very generic
IMHO.
-- 
TZOTZIOY, I speak England very best,
Microsoft Security Alert: the Matrix began as open source.




More information about the Python-list mailing list