欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python3获取前几周和后几周的每周第一天和最后一天日期

程序员文章站 2022-05-10 19:28:26
...

python3获取本周前几周和后几周跨度日期

1.直接上代码

import datetime, time
from datetime import timedelta

# 获取当前周前m周到后n周的每周开始日期和结束日期
def getWeekDaysByNum(m, n):
    # 当前日期
    now = datetime.datetime.now().date()
    dayDict = {}
    for x in range(m, n + 1):
    	#前几周
        if x < 0:
            lDay = now - timedelta(days=now.weekday() + (7 * abs(x)))
        #本周
        elif x == 0:
            lDay = now - timedelta(days=now.weekday())
        #后几周
        else:
            lDay = now + timedelta(days=(7 - now.weekday()) + 7 * (x - 1))
        rDay = lDay + timedelta(days=6)
        dayDict[x] = [str(lDay), str(rDay)]
    return dayDict

2.测试
获取前三周到后三周:
测试代码

print("今天是:" + str(datetime.date.today()))
print("获取跨度日期:" + str(getWeekDaysByNum(-3, 3)))

3.结果
测试结果

今天是:2019-12-04
获取跨度日期:{-3: ['2019-11-11', '2019-11-17'], -2: ['2019-11-18', '2019-11-24'], -1: ['2019-11-25', '2019-12-01'], 0: ['2019-12-02', '2019-12-08'], 1: ['2019-12-09', '2019-12-15'], 2: ['2019-12-16', '2019-12-22'], 3: ['2019-12-23', '2019-12-29']}
相关标签: python2