While working on a data collection project, I needed a way to generate previous month and week datetime objects. For example, to be able to filter all data generated within the past week or the past month. Python's datetime module has fairly robust date and time functionality, but nothing that would fit my requirements. This code is released in the public domain.
from datetime import datetime def reverse_month(): dt = datetime.now() dt = datetime(month=dt.month, day=1, year=dt.year) while True: yield dt m = dt.month y = dt.year if m == 1: m = 12 y = y - 1 else: m = m - 1 dt = datetime(month=m, day=1, year=y)
from datetime import datetime, timedelta def reverse_week(): dt = datetime.date(datetime.now()) while True: if dt.weekday() != 6: dt = dt - timedelta(days=dt.weekday() + 1) else: dt = dt - timedelta(days=7) yield dt
The previous week follows the American convention of Sunday being the first day of the week and Saturday being the last day. Line 6 can be changed to seed the start of the week on any other day.
rmon = reverse_month() rweek = reverse_week() monthseed = datetime.date(datetime.now()) + timedelta(days=1) weekseed = datetime.date(datetime.now()) + timedelta(days=1) while True: tempmon = rmon.next() tempweek = rweek.next() print "%s <= date < %s" % (tempmon, monthseed) print "%s <= date < %s" % (tempweek, weekseed) monthseed = tempmon weekseed = tempweek raw_input()
2010-02-01 00:00:00 <= date < 2010-02-21 2010-02-14 <= date < 2010-02-21 2010-01-01 00:00:00 <= date < 2010-02-01 00:00:00 2010-02-07 <= date < 2010-02-14 2009-12-01 00:00:00 <= date < 2010-01-01 00:00:00 2010-01-31 <= date < 2010-02-07 2009-11-01 00:00:00 <= date < 2009-12-01 00:00:00 2010-01-24 <= date < 2010-01-31 2009-10-01 00:00:00 <= date < 2009-11-01 00:00:00 2010-01-17 <= date < 2010-01-24