我需要获取日期范围内的星期一列表。
例如:
# selected date range
date_range = ['2019-02-25', '2019-03-25']
# desired output:
mondays = ['2019-02-25', '2019-03-04', '2019-03-11', '2019-03-18', '2019-03-25']
# selected date range
date_range = ['2019-02-25', '2019-03-20']
# desired output
mondays = ['2019-02-25', '2019-03-04', '2019-03-11', '2019-03-18']
开始日期始终是星期一。
有谁知道我如何使用python datetime生成星期一列表?
这是使用weekday()的一种方法。
例如:
import datetime
def get_mondays(date_start, date_end):
date_start = datetime.datetime.strptime(date_start, "%Y-%m-%d")
date_end = datetime.datetime.strptime(date_end, "%Y-%m-%d")
result = []
while date_start <= date_end:
if date_start.weekday() == 0: #0 == Monday
result.append(date_start.strftime("%Y-%m-%d"))
date_start += datetime.timedelta(days=1)
return result
print(get_mondays('2019-02-25', '2019-03-25'))
print(get_mondays('2019-02-25', '2019-03-20'))
输出:
['2019-02-25', '2019-03-04', '2019-03-11', '2019-03-18', '2019-03-25']
['2019-02-25', '2019-03-04', '2019-03-11', '2019-03-18']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句