[英]Get dates between two days of the week using Python
I m parsing an html document using python and beautifulSoup where I get strings with the following format, ie workingdates = 'Wednesday-Tuesday'
. 我使用python和beautifulSoup解析html文档,在其中我获得了以下格式的字符串,即
workingdates = 'Wednesday-Tuesday'
。
From that point i get startDate = 'Wednesday'
and endDate = 'Tuesday'
. 从那时起,我得到
startDate = 'Wednesday'
和endDate = 'Tuesday'
。
I want to create a list with all the working days ie list=['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
我想创建一个包含所有工作日的列表,即
list=['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
Any ideas? 有任何想法吗?
You can construct a list of all week days 您可以构建所有工作日的列表
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday', 'Sunday']
and having defined your start and end dates 并定义了开始日期和结束日期
startDate, endDate = 'Wednesday', 'Tuesday'
you can find their positions in the weekdays
list 您可以在
weekdays
列表中找到他们的职位
start = weekdays.index(startDate)
end = weekdays.index(endDate)
there are two possible cases start < end
and start > end
. 有两种可能的情况
start < end
和start > end
。 For the first case you simply take a normal slice. 对于第一种情况,您只需采取普通切片即可。 For the second you slice from
start
to the end of list and append the part from the beginning of the list up to end
. 对于第二个,您从列表的
start
到切片的末尾切片,并将部分从列表的开始追加到end
。
if start < end:
lst = weekdays[start: end+1]
else:
lst = weekdays[start:] + weekdays[:end+1]
You can accomplish this using a list representing a fortnight, by finding the index of the startDate
and the index of the first occurrence of the endDate
after the startDate
: 您可以使用代表两周的列表来完成此操作,方法是查找
startDate
的索引以及startDate
之后首次出现的endDate
的索引:
startDate="Wednesday"
endDate="Tuesday"
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
fortnight = week * 2
start = fortnight.index(startDate)
end = fortnight.index(endDate, start + 1) + 1
workingdays = fortnight[start:end]
print(workingdays)
>>> ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
You can also use cycle
from itertools
: 您还可以从
itertools
使用cycle
:
from itertools import cycle
startDate, endDate = 'Wednesday', 'Tuesday'
l = []
for c in cycle(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']):
if not l and c == startDate:
l.append(c)
elif l and c == endDate:
l.append(c)
break
elif l:
l.append(c)
print(l)
Prints: 印刷品:
['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.