如何从python中的给定日期范围获取sat和sun日期

时间:2011-09-15 03:30:41

标签: python

如何从指定的日期范围获得星期六和星期日的日期。

例如:

  start_date = 2011-09-01
  end_date = 2011-09-15

现在它应该给出输出

2011-09-03
2011-09-04
2011-09-10
2011-09-11

任何帮助都非常感激。

2 个答案:

答案 0 :(得分:4)

>>> import datetime
>>> start = datetime.datetime.strptime("2011-09-01", "%Y-%m-%d")
>>> end = datetime.datetime.strptime("2011-09-15", "%Y-%m-%d")
>>> while start <= end:
...     if start.weekday() in (5, 6):
...         print start.strftime("%Y-%m-%d")
...     start += datetime.timedelta(days=1)
...
2011-09-03
2011-09-04
2011-09-10
2011-09-11
>>>

答案 1 :(得分:2)

嗯,我认为这应该有效:

from datetime import datetime, timedelta

def daterange(start_date, end_date):
  for n in range((end_date - start_date).days):
    yield start_date + timedelta(n)

start_date = '2011-09-01'
end_date = '2011-09-15'
format = '%Y-%m-%d'

start_date_object = datetime.strptime(start_date, format)
end_date_object = datetime.strptime(end_date, format)

for day in daterange(start_date_object, end_date_object):
  if day.weekday() in [5, 6]:
    print day.strftime(format)