Is there a consistent way to enumerate days/weeks/months between two dates?
I have two datetime
objects; a start date and an end date. I need to enumerate the days, weeks and months between the two, inclusive.
Ideally the results would be in datetime
form, though any compatible form is fine. Weeks and months are represented 开发者_如何学JAVAby a date corresponding to the first day of the week/month, where Monday is the first day of a week, as in ISO-8601. This means that the result may contain a date earlier than the start date.
For example, given 2010-11-28 to 2010-12-01, the results would be as follows:
days: 2010-11-28, 2010-11-29, 2010-11-30, 2010-12-01
weeks: 2010-11-22, 2010-11-29
months: 2010-11-01, 2010-12-01
I realize that the list of days is by itself straightforward, but I'd like a clean and consistent solution that uses a similar approach for all three. It seems like the calendar
module should be useful, but I'm not seeing a good way to use it for this purpose.
Using dateutil:
import datetime
import dateutil.rrule as drrule
import dateutil.relativedelta as drel
import pprint
def dt2d(date):
'''
Convert a datetime.datetime to datetime.date object
'''
return datetime.date(date.year,date.month,date.day)
def enumerate_dates(start,end):
days=map(dt2d,drrule.rrule(drrule.DAILY, dtstart=start, until=end))
# Find the Monday on or before start
start_week=start+drel.relativedelta(weekday=drel.MO(-1))
end_week=end+drel.relativedelta(weekday=drel.MO(-1))
weeks=map(dt2d,drrule.rrule(drrule.WEEKLY, dtstart=start_week, until=end_week))
# Find the first day of the month
start_month=start.replace(day=1)
end_month=end.replace(day=1)
months=map(dt2d,drrule.rrule(drrule.MONTHLY, dtstart=start_month, until=end_month))
return days,weeks,months
if __name__=='__main__':
days,weeks,months=enumerate_dates(datetime.date(2010,11,28),
datetime.date(2010,12,01))
print('''\
days: {d}
weeks: {w}
months: {m}'''.format(d=map(str,days),w=map(str,weeks),m=map(str,months)))
yields
days: ['2010-11-28', '2010-11-29', '2010-11-30', '2010-12-01']
weeks: ['2010-11-22', '2010-11-29']
months: ['2010-11-01', '2010-12-01']
精彩评论