Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a range of days in Python

Tags:

python

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

like image 389
Saša Kalaba Avatar asked Jan 20 '16 15:01

Saša Kalaba


People also ask

How do I iterate through days?

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.


2 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]

like image 64
Payne Avatar answered Oct 29 '22 05:10

Payne


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]
like image 39
Robᵩ Avatar answered Oct 29 '22 04:10

Robᵩ