除了周末Python之外的日期时间序列

时间:2014-06-11 16:16:24

标签: python datetime

我试图创建一系列日期时间对象但不包括周末。到目前为止,我已经成功创建了从任何给定开始日期到结束日期的日期序列,但我无法确定如何排除周末:

# Generate sequence of dates
startDate = datetime.datetime.strptime(start, '%Y-%m-%d').date()
endDate = datetime.datetime.strptime(end, '%Y-%m-%d').date()
nb_days = (endDate - startDate).days + 1  # + 1 because range is exclusive
dates = [startDate + datetime.timedelta(days=x) for x in range(nb_days)]

2 个答案:

答案 0 :(得分:7)

isoweekday()函数返回星期几,星期一为1。

[d for d in dates if not d.isoweekday() in [6,7]]

答案 1 :(得分:0)

使用dateutil库的rrule,您可以很好地做到这一点。

示例:

from dateutil.parser import parse
from dateutil.rrule import rrule, DAILY, MO, TU, WE, TH, FR

result = rrule(
  DAILY,
  byweekday=(MO,TU,WE,TH,FR),
  dtstart=parse(start),
  until=parse(end)
)
print(list(result))

示例输出:

[datetime.datetime(2019, 1, 21, 0, 0),
 datetime.datetime(2019, 1, 22, 0, 0),
 datetime.datetime(2019, 1, 23, 0, 0),
 datetime.datetime(2019, 1, 24, 0, 0),
 datetime.datetime(2019, 1, 25, 0, 0),
 datetime.datetime(2019, 1, 28, 0, 0),
 datetime.datetime(2019, 1, 29, 0, 0),
 datetime.datetime(2019, 1, 30, 0, 0),
 datetime.datetime(2019, 1, 31, 0, 0),
 datetime.datetime(2019, 2, 1, 0, 0),
 datetime.datetime(2019, 2, 4, 0, 0)]