What I am trying to accomplish is very simple: creating a loop from a range (pretty self explanatory below) that will insert the month into the datetime object. I know %d requires an integer, and I know that ‘month’ type is int…so I’m kind of stuck as to why I can’t substitute my month variable. Here is my code:
all_months=range(1,13)
for month in all_months:
month_start = (datetime.date(2010,'%d',1))%month
next_month_begin= datetime.date(2010,'%d',1)%(month+1)
month_end=next_month_begin - timedelta(days=1)
print month_start
print month_end
What am I doing wrong?
All help appreciated! Thanks
There are a few things that you need to fix here.
EDIT: First, be careful with your range, since you are using month+1 to create next_month_begin, you do not want this to be greater than 12 or you will get an error.
Next, when you are trying to create the date object you are passing the month in as a string when you use
(datetime.date(2010,'%d',1))%month. Your code probably throwing this errorTypeError: an integer is required.You need to give it the integer representing the month, not a string of the integer (there is a difference between
1and'1'). This is also a simple fix, since you have variable namedmonththat is already an integer, just use that instead of making a string. So you code should be something like:month_start = datetime.date(2010,month,1)I think you can figure out how to apply this to your
next_month_beginassignment.The last problem is that you need to use
datetime.timedeltato tell Python to look in thedatetimemodule for thetimedelta()function — your program would currently give you an error saying that timedelta is not defined.Let me know if you have any problems applying these fixes. Be sure to include what the error you may be getting as well.