How can I get all days between two days?

I need all the weekdays between two days.

Example:

Wednesday - Friday  = Wednesday, Thursday, Friday  
        3 - 5       = 3, 4, 5

 Saturday - Tuesday = Saturday, Sunday, Monday, Tuesday
        6 - 2       = 6, 7, 1, 2

I'm pretty sure there is a clever algorithm out there to solve this. The only algorithms I can think of use either a loop or an if statement.

There has to be an elegant way to solve this. I use the numbers 1-7 for the weekdays, but 0-6 is fine too.

The best I could come up with:

def between(d1, d2):
     alldays = [0,1,2,3,4,5,6,0,1,2,3,4,5,6]    # or range(7) * 2
     offset = 8 if d1 > d2 else 1
     return alldays[d1:d2 + offset]

between(0, 4)
# [0,1,2,3,4]

between(5,2)
# [5,6,0,1,2]

>>> def weekdays_between(s, e):
...     return [n % 7 for n in range(s, e + (1 if e > s else 8))]
... 
>>> weekdays_between(2, 4)
[2, 3, 4]
>>> weekdays_between(5, 1)
[5, 6, 0, 1]

如果您必须将日期转换为实际日期,则会更复杂一些。

>>> days = 'Mon Tue Wed Thu Fri Sat Sun'.split()
>>> days_1 = {d: n for n, d in enumerate(days)}
>>> def weekdays_between(s, e): 
...     s, e = days_1[s], days_1[e]
...     return [days[n % 7] for n in range(s, e + (1 if e > s else 8))]
... 
>>> weekdays_between('Wed', 'Fri')
['Wed', 'Thu', 'Fri']
>>> weekdays_between('Sat', 'Tue')
['Sat', 'Sun', 'Mon', 'Tue']

How about (in pseudo code):

weekday[] = {"Mon" .. "Sun"}
for(i = wkday_start; (i % 7) != wkday_end; i = (i+1) % 7)
    printf("%s ", weekday[i]);

It works like a circular buffer, wkday_start being the index to start at (0-based), wkday_end being the end index.

Hope this helps

George.


基于Stephan202的出色答案,您可以概括圆形切片的概念。

>>> def circular_slice(r, s, e):
... return [r[n % len(r)] for n in range(s, e + (1 if e>s else len(r)+1))]
...
>>> circular_slice(range(0,7), 2, 4)
[2, 3, 4]
>>> circular_slice(range(0,7), 5, 1)
[5, 6, 0, 1]
>>> circular_slice('Mon Tue Wed Thu Fri Sat Sun'.split(), 5, 1)
['Sat', 'Sun', 'Mon', 'Tue']
链接地址: http://www.djcxy.com/p/54882.html

上一篇: C#:从cetain日期添加工作日

下一篇: 我怎样才能在两天之间得到所有的日子?