How to get first/last day of the previous month?
Tim Chase
python.list at tim.thechases.com
Tue Jan 20 10:19:18 EST 2009
> I'm creating a report that is supposed to harvest the data for the
> previous month.
> So I need a way to get the first day and the last day of the previous
> month.
> Would you please tell me how to do this?
>>> from datetime import date, datetime, timedelta
>>> def prev_bounds(when=None):
... if not when: when = datetime.today()
... this_first = date(when.year, when.month, 1)
... prev_end = this_first - timedelta(days=1)
... prev_first = date(prev_end.year, prev_end.month, 1)
... return prev_first, prev_end
...
>>> prev_bounds()
(datetime.date(2008, 12, 1), datetime.date(2008, 12, 31))
>>> prev_bounds(datetime.date(2008,3,14)
(datetime.date(2008, 2, 1), datetime.date(2008, 2, 29))
-tkc
More information about the Python-list
mailing list