是否可以获取所有星期一和星期日并将其存储在嵌套列表/元组中。
Sample data:
dates = [2010-01-01, 2010-01-04, 2010-01-05, 2010-01-06, 2010-01-08, 2010-01-10, 2010-01-11, 2010-01-15, 2010-01-17]
Expected result:
result = ([2010-01-04, 2010-01-10], [2010-01-11, 2010-01-17])
为了阐明预期的结果,我想将
result
与 ([Monday, Sunday], [Monday, Sunday])
分组。 最佳答案
您可以使用 calendar
模块:
import calendar, datetime
def get_day(d):
_d = datetime.date(*map(int, d.split('-')))
c = calendar.Calendar().monthdatescalendar(_d.year, _d.month)
return [i for k in c for i, a in enumerate(k) if a == _d][0]
dates = ['2010-01-01', '2010-01-04', '2010-01-05', '2010-01-06', '2010-01-08', '2010-01-10', '2010-01-11', '2010-01-15', '2010-01-17']
t = [(i, get_day(i)) for i in dates]
sun, mon = [a for a, b in t if b == 6], [a for a, b in t if not b]
输出:
#sun:
['2010-01-10', '2010-01-17']
#mon:
['2010-01-04', '2010-01-11']
编辑:如果您正在寻找输入列表中存在的 mon-sun 范围:
import calendar, datetime
dates = ['2010-01-01', '2010-01-04', '2010-01-05', '2010-01-06', '2010-01-08', '2010-01-10', '2010-01-11', '2010-01-15', '2010-01-17']
d = [datetime.date(*map(int, i.split('-'))) for i in dates]
new_d = [[str(i[0]), str(i[-1])] for j, k in set(map(lambda x:(x.year, x.month), d)) for i in calendar.Calendar().monthdatescalendar(j, k) if i[0] in d and i[-1] in d]
输出:
[['2010-01-04', '2010-01-10'], ['2010-01-11', '2010-01-17']]
关于python - 根据给定的日期范围获取周一和周日,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58986334/