I'm making a schedule app and I need a way to categorize range of days for each block. The days are marked as integers:
MON, TUE, WEN, THU, FRI, SAT, SUN
is 0, 1, 2, 3, 4, 5, 6
So let's say I've scheduled a block that starts Tuesday and ends Friday. Identifying its range is easy:
range(block.start_day, block.end_day +1)
would give me (1, 4)
.
But that won't work if a block starts Saturday and ends Wednesday.
The result I need is (5, 6, 0, 1, 2)
.
I'm kinda stuck at this part. I guess I could use a modulo operator, but I'm not sure.
** EDIT ** I apologize, I've updated the correct desired output.
Using Python 2.7.6
We can use the date_range() function method that is available in pandas. It is used to return a fixed frequency DatetimeIndex. We can iterate to get the date using date() function.
def days(f, L):
if f > L:
x = list(range(0, 7))
return x[f:] + x[:L+1]
else:
return list(range(f, L+1))
days(5, 3)
returns [5, 6, 0, 1, 2, 3]
days(3, 5)
returns [3, 4, 5]
One way to deal with odd ranges is to implement a custom range function:
def date_range(start, end):
'Return a list of weekday values in the range [START, END]'
names = dict(zip(
['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN'],
range(7)))
try:
start = names[start.upper()]
except:
pass
try:
end = names[end.upper()]
except:
pass
while True:
yield start % 7
if start % 7 == end % 7:
return
start += 1
print list(date_range('tue', 'fri'))
print list(date_range('sat', 'wed'))
print list(date_range(5, 2))
Result:
[1, 2, 3, 4]
[5, 6, 0, 1, 2]
[5, 6, 0, 1, 2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With