日期时间序列(周末Python除外) [英] Sequence of datetimes except weekends Python

查看:271
本文介绍了日期时间序列(周末Python除外)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建日期时间对象序列,但不包括周末。到目前为止,我已经成功创建了一个从给定开始日期到结束日期的日期序列,但是我在弄清楚如何排除周末方面遇到了麻烦:

I'm trying to create a sequence of datetime object but excluding weekends. So far I've successfully created a sequence of dates from any given start date to end date, but I'm having trouble figuring out how to exclude weekends:

# 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)]


推荐答案

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

The isoweekday() function returns the day of the week, with 1 a Monday.

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

这篇关于日期时间序列(周末Python除外)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆