Python - 生成从周六到周五的每周日期范围

标签 python

我需要每周运行一份报告,一周从周六开始,到周五结束。但是,由于日期时间或日历模块从星期一开始一周,我无法使用 WEEKDAY 选项。

我尝试了以下选项,但它仍然为我提供了 5 星期六,是否有任何选项可将周开始日设置为星期六,以便星期六为 0 ?这样我就可以从当前日期中减去它以获得所需的日期或任何其他解决方案来实现相同的目标

例如)如果我在 8 月 30 日运行报告,它应该获取 8 月 18 日至 8 月 24 日的数据

import calendar
calendar.setfirstweekday(calendar.SATURDAY)
calendar.firstweekday()
5

最佳答案

感谢帖子Python: give start and end of week data from a given date根据我的需要稍微修改一下

dt = datetime.now()
start = (dt - timedelta(days = (dt.weekday() + 2) % 7))  - timedelta(days=7)
end = (start + timedelta(days=6))
print(start.strftime("%Y-%m-%d"))
print(end.strftime("%Y-%m-%d"))

关于Python - 生成从周六到周五的每周日期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52123788/

相关文章:

python - PEP8 和使用长关键字参数初始化对象

python - 如何在 pymongo (python mongodb) 中执行 get_or_create?

python - 如何求 NumPy 数组的元素模

python - TensorFlow DCGAN 模型 : stability and convergence problems

python - 如何使用opencv将图像显示到PYQT

python - r 网状 OOP 方法失败

python - 为多个函数正确实现(并发)Asyncio

用于创建包含 100 多个视频的 YouTube 播放列表的视频标题列表的 Python 脚本

python - Pyqt5 deleteLater() VS sip.delete()

python - 在文本文件中查找最大匹配区域