Get a range of days in Python

I am creating a schedule application and I need a way to classify a range of days for each block. Days are marked as integers:

MON, TUE, WEN, THU, FRI, SAT, SUN 0, 1, 2, 3, 4, 5, 6

So, let's say I planned a block that starts on Tuesday and ends on Friday. Determining its range is easy:

range(block.start_day, block.end_day +1) would give me (1, 4) .

But this will not work if the block starts on Saturday and ends on Wednesday.

As a result, I need (5, 6, 0, 1, 2) .

I am a bit stuck in this part. I think I could use the modulo operator, but I'm not sure.

** EDIT ** Sorry, I updated the correct desired result.

Using Python 2.7.6

+7
python
source share
5 answers
 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]

+2
source share

One thing you can do is use conditional logic:

 def get_range(start_day, end_day): if (start_day < end_day): r = range(start_day, end_day + 1) else: r1 = range(start_day, 7) r2 = range(0, end_day + 1) r = r1 + r2 return r 

I'm sure someone here might come up with a more elegant solution, but it gets you started.

Just for the sake of thoroughness, I believe the same thing can be done in python 3 (where range creates an iterator, not a list), using itertools.chain instead of + to combine r1 and r2 .

+2
source share

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] 
+2
source share

Here is my solution:

 def get_range(f): week = list(range(7)) if f[1] < f[0]: _curr = week[f[0]:] _rest = week[:f[1]+1] return _curr+_rest else: return range(f[0],f[1]+1) 

result:

 get_range([1,4]) -> [1, 2, 3, 4] get_range([5,2]) -> [5, 6, 0, 1, 2] 
0
source share

You can use this function:

 def getrange(start,end): result = [start] week = [0, 1, 2, 3, 4, 5, 6] c = start while (week[c%7] != end): c = c + 1 result.append(week[c%7]) return result 

Testcases:

 getrange(1,4) =>[1,2,3,4] getrange(5,2) =>[5,6,0,1,2] 
0
source share

All Articles